asp. net Large File Upload Solution Instance Code
- 2021-11-10 09:26:11
- OfStack
ASP. NET, Core, WebAPI is used as the back end API, Vue is used to construct the front end page, and Axios is used to access the back end API from the front end, including uploading and downloading files.
API for preparing file upload
#region File upload You 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 with Form form)
<template>
<div>
<form>
<input type="text" value="" v-model="projectName" placeholder=" Please enter a project name ">
<input type="file" v-on:change="getFile($event)">
<button v-on:click="submitForm($event)"> Upload </button>
</form>
</div>
</template>
<script>
/// This component is used to upload bdls Components of the file
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>
Upload files with Upload component of element-ui
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"> Select a file </el-button>
<el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload"> Upload to server </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: {
// Upload path of file
// Attached users 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();
},
// Hook when file upload is successful
upLoadSuccess(response, file, fileList) {
if (response == "ok") {
console.log(response + " Uploaded " + file);
console.log(" Project Added Successfully ");
} else {
console.log(" Item addition failed ");
}
},
// Hook when file upload fails
upLoadError(response, file, fileList) {
console.log(" Item addition failed ");
}
}
};
</script>
<style lang="scss" scoped>
</style>
File download
The common file download method is to access a background file stream address, directly generate the corresponding file, and download it. The address bar can also carry some control parameters, but the parameters cannot be passed through header.
There are two ways to download files. One is to return file files directly and use the download function of browser. However, this discovery can carry token when sending requests; The other is to use Axios to send a request to download files. header header can be set and token can be carried, but response-type is of blob type.
Type 1:
Back-end 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");
// Object of the file ContentType
var provider = new FileExtensionContentTypeProvider();
var memi = provider.Mappings[fileExt];
return File(stream, memi, Path.GetFileName(addrUrl));
}
The front end uses the browser function url to directly return files
Download files...
downloadRequest() {
let url = "Home/downloadRequest"; // You can pass parameters in the path
window.location.href = url;
},
No. 1 2 Species
Back end api , Two api Is different from the return type of, asp.net core File downloads are 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");
// Object of the file ContentType
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-end page
blob (for storing large binary files)
<el-button type="primary" v-on:click="downloadRequest1"> Download a file 11</el-button>
...
...
...
downloadRequest1() {
axios({
// Use axios Send post Request
method: "post",
url: "Home/downloadRequest1", // Request address You can also pass parameters
headers: {
// Can be customized header
gggg: "gggggggggggggggggggggggggggggggggggggggggggggggggggg" // Can be carried token
},
responseType: "blob" // Indicates the type of data returned by the return server
}).then(res => {
// Processing the returned file stream
// Is mainly to return the data Data passing blob Save as a file
var content = res.data;
var blob = new Blob([content]);
var fileName = "wyy.exe"; // The name of the file to save
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 URL Object
document.body.removeChild(elink);
} else {
// IE10+ Download
navigator.msSaveBlob(blob, fileName);
}
console.log(res);
});
}
Above is the two best use of asp. net file upload solution, you can test, thank you for the support of this site.