Use ASP.NET Core WebAPI as the back-end API, use Vue to build the front-end page, and use Axios to access the back-end API from the front end, including file upload and download.
API for preparing file upload
#region File upload can take parameters
[HttpPost("upload")]
public JsonResult uploadProject(IFormFile file, string userId)
{
if (file != null)
{
var fileDir = "D:\\aaa";
if (!Directory.Exists(fileDir))
{
Directory.CreateDirectory(fileDir);
}
//file name
string projectFileName = file.FileName;
//The path of the uploaded file
string filePath = fileDir + $@"\{projectFileName}";
using (FileStream fs = System.IO.File.Create(filePath))
{
file.CopyTo(fs);
fs.Flush();
}
return Json("ok");
}else{
return Json("no");
}
}
#endregion
Front-end vue upload component (upload using Form form)
<template>
<div>
<form>
<input type="text" value="" v-model="projectName" placeholder="Please enter the project name">
<input type="file" v-on:change="getFile($event)">
<button v-on:click="submitForm($event)">上传</button>
</form>
</div>
</template>
<script>
///This component is used to upload bdls files
export default {
data() {
return {
uploadURL: "/Home/Upload",
projectName: "",
file: ""
};
},
methods: {
getFile(event) {
this.file = event.target.files[0];
console.log(this.file);
},
submitForm(event) {
event.preventDefault();
let formData = new FormData ();
formData.append("file", this.file);
let config = {
headers: {
"Content-Type": "multipart/form-data"
}
};
this.$http
.post(this.uploadURL, formData, config)
.then(function(response) {
if (response.status === 200) {
console.log(response.data);
}
});
}
}
};
</script>
<style lang="scss" scoped>
</style>
Use element-ui's Upload component to upload files
http://element-cn.eleme.io/#/zh-CN/component/upload
<template>
<div>
<el-upload
class="upload-css"
:file-list="uploadFiles"
ref="upload"
:on-success="upLoadSuccess"
:on-error="upLoadError"
:action="uploadURL"
:auto-upload="false">
<el-button slot="trigger" size="small" type="primary">选取文件</el-button>
<el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
</el-upload>
</div>
</template>
<script>
import Vue from "vue";
import { Upload, Button } from "element-ui";
Vue.use(Upload);
Vue.use(Button);
export default {
props: [],
data() {
return {
projectName: "",
//uploadURL: "/project/upload?a=1",
uploadFiles: [] //List of uploaded files
};
},
computed: {
//File upload path
//With user id and project name
uploadURL: function() {
//var userId = this.$store.state.userId;
return "/project/upload?userId=" + 1;
}
},
methods: {
//File Upload
submitUpload() {
this.$refs.upload.submit();
},
//The hook when the file upload is successful
upLoadSuccess(response, file, fileList) {
if (response == "ok") {
console.log(response + "Uploaded" + file);
console.log("Project added successfully");
} else {
console.log("Project addition failed");
}
},
//The hook when the file upload fails
upLoadError(response, file, fileList) {
console.log("Project addition failed");
}
}
};
</script>
<style lang="scss" scoped>
</style>
Download Document
The ordinary file download method is to access a background file stream address, directly generate the corresponding file, and just download it. The address bar can also carry some control parameters, but the parameters cannot be passed through the header.
There are two file downloading methods, one is to directly return to the file file and use the download function of the browser. However, it is not found that the token can be carried when sending the request; the other is to use Axios to send the download file request, which can set the header and carry the token, but the response-type is of blob type.
The first:
Backend API:
public FileResult downloadRequest()
{
//var addrUrl = webRootPath + "/upload/thumb.jpg";
var addrUrl = "D:/aaa/thumb.jpg";
var stream = System.IO.File.OpenRead(addrUrl);
string fileExt = Path.GetExtension("thumb.jpg");
//Get the ContentType of the file
var provider = new FileExtensionContentTypeProvider();
var memi = provider.Mappings [fileExt];
return File(stream, memi, Path.GetFileName(addrUrl));
}
The front end uses the browser's functional url to directly return the file
download file...
...
...
downloadRequest() {
let url = "Home/downloadRequest"; //You can pass parameters in the path
window.location.href = url;
},
The second
Back-end api, the return types of the two apis are different, asp.net core file downloads commonly used FileResult, FileContentResult, FileStreamResult.
public FileContentResult downloadRequest1()
{
//string webRootPath = _hostingEnvironment.WebRootPath;
//var addrUrl = webRootPath + "/upload/thumb.jpg";
var addrUrl = "D:/aaa/wyy.exe";
/*var stream = System.IO.File.OpenRead(addrUrl);
string fileExt = Path.GetExtension("thumb.jpg");
//Get the ContentType of the file
var provider = new FileExtensionContentTypeProvider();
var memi = provider.Mappings [fileExt];
return File(stream, memi, Path.GetFileName(addrUrl));*/
//return stream;
byte[] fileBytes = System.IO.File.ReadAllBytes(addrUrl);
string fileName = "wyy.exe";
return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName); //Key statement
}
Front page
blob (used to store large binary files)
<el-button type="primary" v-on:click="downloadRequest1">下载文件11</el-button>
...
...
...
downloadRequest1() {
axios({
// Send post request with axios
method: "post",
url: "Home/downloadRequest1", // Request address, you can also pass parameters
headers: {
//You can customize the header
gggg: "ggggggggggggggggggggggggggggggggggggggggggggggggggggg" // 可以 携带 token
},
responseType: "blob" // indicates the type of data returned by the server
}).then(res => {
// Process the returned file stream
//Mainly save the returned data into a file through blob
var content = res.data;
var blob = new Blob([content]);
var fileName = "wyy.exe"; //The name of the file to be saved
if ("download" in document.createElement("a")) {
// Non-IE download
var elink = document.createElement("a");
elink.download = fileName;
elink.style.display = "none";
elink.href = URL.createObjectURL(blob);
document.body.appendChild(elink);
elink.click();
URL.revokeObjectURL(elink.href); // release the URL object
document.body.removeChild(elink);
} else {
// IE10+ download
navigator.msSaveBlob(blob, fileName);
}
console.log(res);
});
}
The third
Just use the up6 control, this control supports mac, windos, Linux, because it is too long, you can refer to this article for details: http://blog.ncmem.com/wordpress/2019/08/09/asp- net%e6%96%87%e4%bb%b6%e4%b8%8a%e4%bc%a0%e4%b8%8b%e8%bd%bd/
Welcome to join the group to discuss together: 374992201