.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相结合而成的文件上传插件,其功能非常强大.以前在项目中用过几次,但它的配置参数太多了,用过后就忘记怎么用了,到以后要用时又得到官网上看它的文档,真是太烦了.所以 ...
随机推荐
- 在Centos下使用Siege对Django服务进行压力测试
Siege是linux下的一个web系统的压力测试工具,支持多链接,支持get和post请求,可以对web系统进行多并发下持续请求的压力测试.今天我们就使用Siege来对Django进行一次压力测试, ...
- 正方形和球体,利用蒙特卡洛计算pi值
clc; clear all; close all; R = 3; time = 10000; origin = [0,0,0]; %%======绘制球体====== t=linspace(0,pi ...
- jquery ajax return不起作用
jquery的ajax方法:在success中使用return:来结束程序的时候,结束的只是success这个方法,也就是说success中的return的作用范围只是success: 如果要想在su ...
- jQuery中live()使用报错,TypeError: $(...).live is not a function
原博文 https://blog.csdn.net/sdfdyubo/article/details/59536781 使用 原写法 /*为选项卡绑定右键*/ $(".tabs li&quo ...
- NAT、端口映射、内网穿透、公网IP都是啥
原文地址:https://wuter.cn/1756.html/ 一.IPv4地址 IP协议是为计算机网络相互连接进行通信而设计的协议,它是能使连接到网上的所有计算机网络实现相互通信的一套规则. 这里 ...
- 为什么MySQL不推荐使用uuid作为主键?
前言 在mysql中设计表的时候,mysql官方推荐不要使用uuid或者不连续不重复的雪花id(long形且唯一,单机递增),而是推荐连续自增的主键id,官方的推荐是auto_increment,那么 ...
- 远程桌面连接(出现身份验证错误。要求的函数不支持)这可能由于CredSSP加密Oracle修正。
家庭版解决方案 在进行远程桌面时会遇到这种情况.对于Windows 10家庭版用户,是不支持组策略功能的.本文根据官方文档采用修改注册表的方式达到相同的目的. 1.打开注册表 win + R 键 ...
- Java学习日报7.24
package tem; public class Tem { public static void main(String[] args) { // TODO 自动生成的方法存根 //每隔10摄氏度 ...
- Pytest测试框架(三):pytest fixture 用法
xUnit style 结构的 fixture用于初始化测试函数, pytest fixture是对传统的 xUnit 架构的setup/teardown功能的改进.pytest fixture为测试 ...
- git基础-撤销操作
---恢复内容开始--- 撤销操作 在任何阶段,你都有可能想要撤销某些操作. 当我们提交完了代码,发现漏掉了几个文件没有添加,后者提交信息写错了,此时,可以运行--amend选项的提交命令尝试重新提交 ...