Asp.net large file upload solution example code

Time:2020-5-19

Asp.net core web API is used as the back-end API, Vue is used to build the front-end page, and Axios is used to access the back-end API from the front-end, including file upload and download.

Prepare API for file upload

#Region file can be uploaded with 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;

 

    //Path to the uploaded file

    string filePath = fileDir + [email protected]"\{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 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 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>

Upload files with the upload component of element UI

http://element-cn.eleme.io/#/zh-CN/component/upload

<template>

<div>

 <el-upload

 

  :file-list="uploadFiles"

  ref="upload"

  :on-success="upLoadSuccess"

  :on-error="upLoadError"

  :action="uploadURL"

  :auto-upload="false">

  Select 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

 //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();

 },

 //File upload成功时的钩子

 upLoadSuccess(response, file, fileList) {

  if (response == "ok") {

  Console.log (response + "uploaded" + file);

  console.log ("project added successfully");

  } else {

  Console.log ("failed to add project");

  }

 },

 //File upload失败时的钩子

 upLoadError(response, file, fileList) {

  Console.log ("failed to add project");

 }

 }

};

</script>

 

<style lang="scss" scoped>

</style>

File download

The common method of file download is to access a background file stream address and directly generate the corresponding file. You can download it, and the address bar can also carry some control parameters, but you can’t pass the parameters through the header.

There are two ways to download files. 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 a request; the other is to use Axios to send a request to download a file. The header header can be set to 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 contenttype of file

 

   var provider = new FileExtensionContentTypeProvider();

 

   var memi = provider.Mappings[fileExt];

 

   return File(stream, memi, Path.GetFileName(addrUrl));

  }

The front end uses the function URL of browser to return files directly

Download File

downloadRequest() { 

 Let url = "home / downloadrequest"; // parameters can be passed in the path

 window.location.href = url;

 },

The second

Back end API. The return types of the two APIs are different. Fileresult, filecontentresult and filestreamresult are commonly used for asp.net core file download.

 

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 contenttype of 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" > Download file11 < / El button >

...

...

...

 downloadRequest1() {

  axios({

  //Send post request with Axios

  method: "post",

  URL: "home / downloadrequest1", // request address, or pass parameters

  headers: {

   //You can customize the header

   Gggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggg

  },

  Responsetype: "blob" // indicates the data type returned by the server

  }).then(res => {

  //Process the returned file stream

  //The main purpose is to 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 save

  if ("download" in document.createElement("a")) {

   //Non ie Downloads

   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 are the two best solutions for uploading large asp.net files. You can test them. Thank you for your support for developepaer.