.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相结合而成的文件上传插件,其功能非常强大.以前在项目中用过几次,但它的配置参数太多了,用过后就忘记怎么用了,到以后要用时又得到官网上看它的文档,真是太烦了.所以 ...
随机推荐
- 【Go语言绘图】图片添加文字(一)
前一篇讲解了利用gg包来进行图片旋转的操作,这一篇我们来看看怎么在图片上添加文字. 绘制纯色背景 首先,我们先绘制一个纯白色的背景,作为添加文字的背景板. package main import &q ...
- 【windows】【消息中间件】【安装】Elasticsearch
一.准备工作 elasticsearch的下载地址:https://www.elastic.co/cn/downloads/elasticsearch ik分词器的下载地址:https://githu ...
- spark 系列之一 RDD的使用
spark中常用的两种数据类型,一个是RDD,一个是DataFrame,本篇主要介绍RDD的一些应用场景见代码本代码的应用场景是在spark本地调试(windows环境) /** * 创建 spark ...
- C语言I博客作业1
1 .班级链接: https://edu.cnblogs.com/campus/zswxy/SE2020-3 2 .作业要求链接: https://edu.cnblogs.com/campus/zsw ...
- 多线程并行_countDown
/** * 首次启动加载数据至缓存 */ public class ApplicationStartTask { private static Logger logger = LoggerFactor ...
- Eclipse导入外部jar包的步骤
(1)首先在项目的跟目录下先建一个名字为lib的文件夹,通常外部导入的jar包都放在这个文件夹下面. (2)将需要用到的jar包复制到lib文件夹下面. (3)在项目中导入jar包 右键项目,选择Bu ...
- 如何在Linux(CentOS7)环境搭建 Jenkins 服务器环境
最近,我自己要亲手搭建一套完整的企业级 CI/CD 环境,这个环节里面涉及了很多内容,没有办法把这么多的内容都放在一篇文章里,所以 Jenkins 的安装和Java 的 JDK 安装我就是分了两篇文章 ...
- Head First 设计模式 —— 07. 适配器模式
思考题 你能想到真实世界中,还有哪些适配器的例子? P236 HDMI 转 VGA 转换器 Type-C 转 3.5mm 线 适配器模式解析 客户使用适配器的过程: P241 客户通过目标接口调用适配 ...
- C++ 入门篇
C++基础入门 1 C++初识 1.1 第一个C++程序 编写一个C++程序总共分为4个步骤 创建项目 创建文件 编写代码 运行程序 1.1.1 创建项目 Visual Studio是我们用来编写 ...
- 了解一下RPC,为何诞生RPC,和HTTP有什么不同?
了解一下RPC,为何诞生RPC,和HTTP有什么不同? 开篇提问 什么是RPC? 为什么需要RPC,用来解决什么问题? RPC与HTTP有什么不同? 你知道几种RPC? 认识RPC RPC:Remot ...