.net code+vue 文件上传
后端技术
.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 文件上传的更多相关文章
- Spring Boot 2.x(十六):玩转vue文件上传
为什么使用Vue-Simple-Uploader 最近用到了Vue + Spring Boot来完成文件上传的操作,踩了一些坑,对比了一些Vue的组件,发现了一个很好用的组件--Vue-Simple- ...
- 测试开发实战[提测平台]17-Flask&Vue文件上传实现
微信搜索[大奇测试开],关注这个坚持分享测试开发干货的家伙. 先回顾下在此系列第8次分享给出的预期实现的产品原型和需求说明,如下图整体上和前两节实现很相似,只不过一般测试报告要写的内容可能比较多,就多 ...
- vue文件上传
今天写一个文件上传的功能,开始想用element-ui的组件写,但是发现不知道怎么把文件标题和内容一起上传,所以用了经典的input框上传. 废话不多说,直接上代码. 这是表单: <el-for ...
- vuetify | vue | 文件上传组件 | file | upload | form input[type="file"]
今天无聊地写vuecli3听歌的时候,遇到了上传文件到Django的自我需求,然后就到vuetify的表单组件里找upload btn,发现居然没有!!! 顿时惊了个呆,要知道之前用element做操 ...
- vue文件上传及压缩(canvas实现压缩)
// 读取文件结果 afterRead(files) { let that = this; let file = files.file; if (file === undefined) { retur ...
- vue文件上传控件
下载地址:https://pan.baidu.com/s/1Z3pFh2J3xWa8YYnLoseasg 使用方式: <upload ref='upload' action-url='' :mu ...
- 文件上传利器SWFUpload使用指南(转)
http://www.cnblogs.com/2050/archive/2012/08/29/2662932.html 文件上传利器SWFUpload使用指南 SWFUpload是一个flash和js ...
- SWFUpload文件上传详解
SWFUpload是一个flash和js相结合而成的文件上传插件,其功能非常强大. SWFUpload的特点: 1.用flash进行上传,页面无刷新,且可自定义Flash按钮的样式; 2.可以在浏览器 ...
- SwfUpload文件上传
SWFUpload是一个flash和js相结合而成的文件上传插件,其功能非常强大.以前在项目中用过几次,但它的配置参数太多了,用过后就忘记怎么用了,到以后要用时又得到官网上看它的文档,真是太烦了.所以 ...
随机推荐
- C#中的深度学习(三):理解神经网络结构
在这篇文章中,我们将回顾监督机器学习的基础知识,以及训练和验证阶段包括哪些内容. 在这里,我们将为不了解AI的读者介绍机器学习(ML)的基础知识,并且我们将描述在监督机器学习模型中的训练和验证步骤. ...
- js Table表格选中一行变色或者多选 并获取值
使用JQ <script> let old, oldColor; $("#sp_body tr").click(function (i) { if (old) oldC ...
- Git常用命令大全,迅速提升你的Git水平
原博文 https://mp.weixin.qq.com/s/hYjGyIdLK3UCEVF0lRYRCg 示例 初始化本地git仓库(创建新仓库) git init ...
- Java获取某年某月的第一天和最后一天
/** * 获取某年某月的第一天 * @Title:getFisrtDayOfMonth * @Description: * @param:@param year * @param:@param mo ...
- 还在使用Future轮询获取结果吗?CompletionService快来了解下吧。
背景 二胖上次写完参数校验(<二胖写参数校验的坎坷之路>)之后,领导一直不给他安排其他开发任务,就一直让他看看代码熟悉业务.二胖每天上班除了偶尔跟坐在隔壁的前端小姐姐聊聊天,就是看看这些 ...
- Mac电脑 Android Studio连接小米手机
1.设置>关于本机>点击5下MIUI版本>激活开发者模式 2.设置>更多设置>开发者选项>开启开发者选项>开启USB调试>开启USB安装>开启显示 ...
- springboot文件上传问题记录
最近做项目需要开发一个通过excel表格导入数据的功能,上传接口写好调试的时候遇到几个问题,记录一下. 报错1: 15:50:57.586 [[1;33mhttp-nio-8763-exec-8 [0 ...
- 前端面试题归类-HTML2
一. SGML . HTML .XML 和 XHTML 的区别? SGML 是标准通用标记语言,是一种定义电子文档结构和描述其内容的国际标准语言,是所有电子文档标记语言的起源. HTML 是超文本标记 ...
- java并发包工具(java.util.Concurrent)
一.CyclicBarrier 作用:所有线程准备好才进行,只要一条线程没准备好,都不进行 用法:所有线程准备好以后调用CyclicBarrier的await方法,然后主线程执行CyclicBarri ...
- haproxy 支持 websocket
haproxy支持websocket feat 通过嗅探http请求中的Connection: Upgrade Upgrade: websocket头部,来自动识别是否是websocket连接,识别成 ...