后端技术

.net code 官方文档 https://docs.microsoft.com/zh-cn/aspnet/core/mvc/models/file-uploads?view=aspnetcore-3.1

上传方式:multipart/form-data

其他参数:Name,Version,Type

方法1:自定义解析

[ApiController]
[Route("api/[controller]")]
public class UploadController : ControllerBase
{
  private const string fileRootPath = "D://files";
  [HttpPost]
  [DisableFormValueModelBinding]
  [Route("UploadFile")]
  public async Task<ApiResult<FileUploadResponse>> UploadFile()
  {
    FileUploadResponse datas = new FileUploadResponse();
    var reader = new MultipartReader(HeaderUtilities.RemoveQuotes((MediaTypeHeaderValue.Parse(Request.ContentType)).Boundary).Value, HttpContext.Request.Body);
    MultipartSection section = await reader.ReadNextSectionAsync();
    while (section != null)
    {
      try
      {
        if (!ContentDispositionHeaderValue.TryParse(section.ContentDisposition, out var contentDisposition)
          || contentDisposition == null
          || !contentDisposition.DispositionType.Equals("form-data"))
        {
          continue;
        }
        using (var memoryStream = new MemoryStream())
        {
          await section.Body.CopyToAsync(memoryStream);
          string fileName = contentDisposition.FileName.Value;
          string name = contentDisposition.Name.Value;
          if (string.IsNullOrWhiteSpace(fileName))
          {
            var encoding = GetEncoding(section);
            string value = encoding.GetString(memoryStream.ToArray());
            datas.Propertys.Add(new KeyValuePair<string, string>(name, value));
            continue;
          }
          fileName = Guid.NewGuid().ToString("N") + Path.GetExtension(fileName);
          datas.FileNames.Add(fileName);
          using (var targetStream = System.IO.File.Create(Path.Combine(fileRootPath, fileName)))
          {
            await targetStream.WriteAsync(memoryStream.ToArray());
          }
        }
      }
      finally
      {
        section = await reader.ReadNextSectionAsync();
      }
    }
    return ResultState.Success(datas);
  }
}

移除.netCode默认

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class DisableFormValueModelBindingAttribute : System.Attribute, IResourceFilter
{
  public void OnResourceExecuting(ResourceExecutingContext context)
  {
    var factories = context.ValueProviderFactories;
    factories.RemoveType<FormValueProviderFactory>();
    factories.RemoveType<FormFileValueProviderFactory>();
    factories.RemoveType<JQueryFormValueProviderFactory>();
  }
  public void OnResourceExecuted(ResourceExecutedContext context)
  {
  }
}

返回值模型类

public class FileUploadResponse
{
  public List<KeyValuePair<string, string>> Propertys { get; set; } = new List<KeyValuePair<string, string>>();
  public List<string> FileNames { get; set; } = new List<string>();
}

方法二:使用IFormFile

[ApiController]
[Route("api/[controller]")]
public class UploadController : ControllerBase
{
  private const string fileRootPath = "D://files";
  [HttpPost]
  [Route("UploadFiles")]
  public async Task<ApiResult<FileUploadResponse>> UploadFiles([FromForm]FileUploadRequest data)
                                     //(IFormFile file, [FromForm] string name, [FromForm] string version, [FromForm] FileUploadType type)
                                     //([FromForm]List<IFormFile> files, [FromForm]string name)
  {
    var result = new FileUploadResponse();
    result.Propertys.Add(new KeyValuePair<string, string>("Name", data.Name));
    result.Propertys.Add(new KeyValuePair<string, string>("Version", data.Version));
    result.Propertys.Add(new KeyValuePair<string, string>("Type", data.Type));     string suffix = Path.GetExtension(data.File.FileName);
    string fileName = data.File.FileName + "_" + Guid.NewGuid().ToString("N") + suffix;
    using (var stream = new FileStream(Path.Combine(fileRootPath, fileName), FileMode.Create))
    {
      await data.File.CopyToAsync(stream);
    }
    result.FileNames.Add(fileName);
    return ResultState.Success(result);
  }
}

请求模型类和返回值模型类

public class FileUploadRequest
{
public IFormFile File { get; set; }
public string Name { get; set; }
public string Version { get; set; }
public string Type { get; set; }
}
public class FileUploadResponse
{
public List<KeyValuePair<string, string>> Propertys { get; set; } = new List<KeyValuePair<string, string>>();
public List<string> FileNames { get; set; } = new List<string>();
}

前端技术

前端采用vuex+element-ui

element-ui官网:https://element.eleme.cn/#/zh-cn/component/upload

方式1:el-upload action 提交

<template>
<div>
<el-form :model="form" :rules="rules" ref="form" label-width="150px">
<el-form-item label="名称" prop="name">
<el-input v-model="form.name" placeholder="请填写名称"/>
</el-form-item>
<el-form-item label="版本号" prop="version">
<el-input v-model="form.version" placeholder="请填写版本号"/>
</el-form-item>
<el-form-item label="类型" prop="type">
<el-input v-model="form.type" placeholder="请填写类型"/>
</el-form-item>
<el-form-item label="上传文件" prop="path">
<el-upload
action="http://localhost:5001/api/FileUpload/UploadifyFile"
:before-upload="beforeUpload"
:show-file-list="false"
:data="extraData()"
:on-success="uploadSuccess"
>
<el-button size="small" type="primary">点击上传</el-button>
<span>{{this.form.path}}</span>
</el-upload>
</el-form-item>
</el-form>
<br>
</div>
</template> <script>
export default {
data() {
return {
rules: {
name: [ { required: true, message: "请填写名称", trigger: "blur" } ],
version: [ { required: true, message: "请填写版本号", trigger: "blur" } ],
type: [ { required: true, message: "请填写类型", trigger: "blur" } ],
path: [ { required: true, message: "请选择文件", trigger: "blur" } ]
},
form: {
name: undefined,
version: undefined,
type: undefined,
path: undefined
}
}
},
methods: {
extraData() {
return {
"name": this.form.name,
"version": this.form.version,
"type": this.form.type
}
},
uploadSuccess(response, file, fileList){
this.form.path = response.data.fileName;
},
beforeUpload(file)
{
if(this.form.name == null || this.form.name === ""){
this.$message.error('请填写名称');
return false;
}
if(this.form.version == null || this.form.version === ""){
this.$message.error('请填写版本号');
return false;
}
if(this.form.type == null || this.form.type === ""){
this.$message.error('请填写类型');
return false;
}
return true;
}
}
}
</script>

方法二:axios提交

<template>
<div>
<el-form :model="form" :rules="rules" ref="form" label-width="150px">
<el-form-item label="名称" prop="name">
<el-input v-model="form.name" placeholder="请填写名称"/>
</el-form-item>
<el-form-item label="版本号" prop="version">
<el-input v-model="form.version" placeholder="请填写版本号"/>
</el-form-item>
<el-form-item label="类型" prop="type">
<el-input v-model="form.type" placeholder="请填写类型"/>
</el-form-item>
<el-form-item label="上传文件" prop="path">
<el-upload
action=""
:before-upload="beforeUpload"
:show-file-list="false"
:data="extraData()"
:http-request="handleHttpRequest">
<el-button size="small" type="primary">点击上传</el-button>
<span>{{this.form.path}}</span>
</el-upload>
</el-form-item>
</el-form>
<br>
</div>
</template> <script>
import axios from "axios";
export default {
data() {
return {
rules: {
name: [ { required: true, message: "请填写名称", trigger: "blur" } ],
version: [ { required: true, message: "请填写版本号", trigger: "blur" } ],
type: [ { required: true, message: "请填写类型", trigger: "blur" } ],
path: [ { required: true, message: "请选择文件", trigger: "blur" } ]
},
form: {
name: undefined,
version: undefined,
type: undefined,
path: undefined
}
}
},
methods: {
extraData() {
return {
"name": this.form.name,
"version": this.form.version,
"type": this.form.type
}
},
handleHttpRequest(fileDatas){
var fd = new FormData();
for (let prop in fileDatas.data) {
fd.append(prop, fileDatas.data[prop]);
}
fd.append("file", fileDatas.file); let config = {
headers: {
'Content-Type': 'multipart/form-data'
}
} axios.post("http://localhost:5001/api/FileUpload/UploadifyFile", fd, config).then(response =>
{
console.log(response);
this.form.path = response.data.data.fileName;
});
},
beforeUpload(file)
{
if(this.form.name == null || this.form.name === ""){
this.$message.error('请填写名称');
return false;
}
if(this.form.version == null || this.form.version === ""){
this.$message.error('请填写版本号');
return false;
}
if(this.form.type == null || this.form.type === ""){
this.$message.error('请填写类型');
return false;
}
return true;
}
}
}
</script>

.net code+vue 文件上传的更多相关文章

  1. Spring Boot 2.x(十六):玩转vue文件上传

    为什么使用Vue-Simple-Uploader 最近用到了Vue + Spring Boot来完成文件上传的操作,踩了一些坑,对比了一些Vue的组件,发现了一个很好用的组件--Vue-Simple- ...

  2. 测试开发实战[提测平台]17-Flask&Vue文件上传实现

    微信搜索[大奇测试开],关注这个坚持分享测试开发干货的家伙. 先回顾下在此系列第8次分享给出的预期实现的产品原型和需求说明,如下图整体上和前两节实现很相似,只不过一般测试报告要写的内容可能比较多,就多 ...

  3. vue文件上传

    今天写一个文件上传的功能,开始想用element-ui的组件写,但是发现不知道怎么把文件标题和内容一起上传,所以用了经典的input框上传. 废话不多说,直接上代码. 这是表单: <el-for ...

  4. vuetify | vue | 文件上传组件 | file | upload | form input[type="file"]

    今天无聊地写vuecli3听歌的时候,遇到了上传文件到Django的自我需求,然后就到vuetify的表单组件里找upload btn,发现居然没有!!! 顿时惊了个呆,要知道之前用element做操 ...

  5. vue文件上传及压缩(canvas实现压缩)

    // 读取文件结果 afterRead(files) { let that = this; let file = files.file; if (file === undefined) { retur ...

  6. vue文件上传控件

    下载地址:https://pan.baidu.com/s/1Z3pFh2J3xWa8YYnLoseasg 使用方式: <upload ref='upload' action-url='' :mu ...

  7. 文件上传利器SWFUpload使用指南(转)

    http://www.cnblogs.com/2050/archive/2012/08/29/2662932.html 文件上传利器SWFUpload使用指南 SWFUpload是一个flash和js ...

  8. SWFUpload文件上传详解

    SWFUpload是一个flash和js相结合而成的文件上传插件,其功能非常强大. SWFUpload的特点: 1.用flash进行上传,页面无刷新,且可自定义Flash按钮的样式; 2.可以在浏览器 ...

  9. SwfUpload文件上传

    SWFUpload是一个flash和js相结合而成的文件上传插件,其功能非常强大.以前在项目中用过几次,但它的配置参数太多了,用过后就忘记怎么用了,到以后要用时又得到官网上看它的文档,真是太烦了.所以 ...

随机推荐

  1. AD PCB模块复用

    该文档为原创,转发需注明出处!https://www.cnblogs.com/brianblog/ 在画图的时候如果遇到PCB中有多个模块原理图是一模一样的时候,我们便会想能不能偷点懒,只画一个模块, ...

  2. sqli-labs 20-22 --cookie注入

    异常处理 一开始打开这个题目的时候找不到cookie... 登录成功就是没有cookie cookie注入没有cookie... 第二天重新做的时候,同学讲自己设置cookie可以用 用插件EditT ...

  3. Docker来搭建分布式文件系统FastDfs

    对于文件存储来说,一般情况下简单的处理就是在Django配置文件中配置存储目录,按照规则对文件进行上传或者下载. 实际上,当文件较少的时候,Django是可以应付的过来的.但当文件以海量形式出现的时候 ...

  4. JavaScript之经典面试题

    1.作用域经典面试题 var num = 123; // f1函数写好了,作用域就定下来了,也就是作用域链定下来了 // f1函数作用域链: f1函数作用域 ==> 全局作用域 function ...

  5. (十五)、shell脚本之简单控制流结构

    一.基本的控制结构 1.控制流 常见的控制流就是if.then.else语句提供测试条件,测试条件可以基于各种条件.例如创建文件是否成功.是否有读写权限等,凡是执行的操作有失败的可能就可以用控制流,注 ...

  6. 转载--对batch normalization的理解

    转载的大神的: https://www.cnblogs.com/guoyaohua/p/8724433.html 上边这个应该是抄的下边这个原文,但是上边的有重点标记 https://blog.csd ...

  7. JDBC访问数据库的基本步骤是什么?

    1.加载(注册)数据库驱动(到JVM) 2.建立(获取)数据库连接. 3.创建(获取)数据库操作对象. 4.定义操作的SQL语句. 5.执行数据库操作. 6.获取并操作结果集. 7.关闭对象,回收数据 ...

  8. 为什么 StackOverflow 上的代码片段会摧毁你的项目?

    昨天公司里碰到一件令人哑然失笑的事情.帮朋友公司做的一个项目,做SIT测试的时候发现一些bug,仔细查了下原因,原来是因为当初觉得这个项目比较简单,交给了几个新入职的新丁,也算是给他们练练手,结果其中 ...

  9. JavaScript 函数节流和函数去抖

    概念 函数防抖(debounce) 当调用动作过n毫秒后,才会执行该动作,若在这n毫秒内又调用此动作则将重新计算执行时间 函数节流(throttle) 预先设定一个执行周期,当调用动作的时刻大于等于执 ...

  10. 「译」使用 System.Net.Http.Json 高效处理Json

    在这篇文章,我将介绍一个名为 System.Net.Http.Json 的扩展库,它最近添加到了 .NET 中,我们看一下这个库能够给我们解决什么问题,今天会介绍下如何在代码中使用. 在此之前我们是如 ...