Upload and download of. NET Core Files

Source: Internet
Author: User

1. Preface

File import and export is a simple and common function, the following example implements the file upload and download several methods, if there is something wrong, please correct me. Small white one, moving toward the target.

2.1. File upload--Pure file
1 <formAction= "/home/index"Method= "POST"enctype= "Multipart/form-data" > 2     <inputtype= "File"multiple/>3     <inputID= "Upload"type= "Submit" />4 </form>
1 [HttpPost]2          Publiciactionresult Index (list<iformfile> files)3         {4            5             foreach(varFileinch files)6             {7                 //Get file name8                 varFileName =file. FileName;9                 //save under the Wwwroot folderTenFileName = Hostingenv.webrootpath + $"\\{filename}"; A                 using(FileStream fs =System.IO.File.Create (fileName)) -                 { - file. CopyTo (FS); the FS. Flush (); -                 } -             } -             returnView (); +}
2.2. File upload-multi-type content upload

For a form that is not just a file, you can use model binding.

 <FormAction= "/home/index"Method= "POST"Enctype= "Multipart/form-data">
<input type= "file" Multiple/>
<input type= "text" name= "name" />
<input id= "upload" Type= "submit" />
</form>
        /// <summary>        ///form upload file/// </summary>        /// <param name= "Files" ></param>        /// <returns></returns>[HttpPost] Publiciactionresult Index (Formobject obj) {foreach(varFileinchobj. Files) {//Get file name                varFileName =Contentdispositionheadervalue. Parse (file. contentdisposition). FileName. Trim ('"'); FileName= Hostingenv.webrootpath + $"\\{filename}"; using(FileStream fs =System.IO.File.Create (FileName)) {file.                    CopyTo (FS); Fs.                Flush (); }            }            returnView (); }

// Model Class  Public class formobject{       publicgetset;}         Public string Get Set ; }}
2.3. File upload--Ajax upload
    <inputtype= "text"name= "Name"value= "123"/>        <inputtype= "File"ID= "FileUpload"name= "FileUpload"multiple/>    <inputID= "Upload"type= "button"value= "Ajax Commit"/>
<script type= "Text/javascript" >    $(function () {        $("#upload"). Click (function(evt) {///Take selected files to join Formdata            varFileUpload = $ ("#fileUpload"). Get (0); varFiles =Fileupload.files; vardata =NewFormData ();  for(vari = 0; i < files.length; i++) {data.append (Files[i].name, files[i]); }           //data.append ("name", $ (' input[name= "name"] "). Val ())$.ajax ({type:"POST", URL:"Http://192.168.0.175:8095/api/Organization", ContentType:false, ProcessData:false, Data:data, success:function(message) {alert (message); }, Error:function() {alert ("There was an error uploading the file! ");        }            });    }); });</script>
        /// <summary>        ///uploading via Ajax/// </summary>        /// <returns></returns>         PublicIactionresult uploadfiles () {varFiles =Request.Form.Files; varValue =request.form.first (c = C.key = ="Name"). value;//getting form text Itemsforeach(varFileinchfiles) {                varFileName =file. FileName;FileName = Hostingenv.webrootpath + $@"\{filename}";using(FileStream fs =System.IO.File.Create (FileName)) {file.                    CopyTo (FS); Fs.                Flush (); }            }            returnRedirecttoaction ("/export",New{Title ="1", Name =123}); }
3.3. File download
1 [HttpGet]2          Publiciactionresult exporttext ()3         {4            5             stringsFileName = $@"qmhuangtext{datetime.now.tostring ("Yyyymmddhhmmss")}.txt";6FileStream fs =NewFileStream (sfilename,filemode.openorcreate);7StreamWriter SW =NewStreamWriter (FS);8Sw. WriteLine ("Hello World");9 SW. Flush ();Ten SW. Close (); One FS. Close (); A             returnFile (NewFileStream (sFileName, FileMode.Open),"Application/octet-stream", $"Export Test {DateTime.Now.ToString ("Yyyymmddhhmmss")}.txt"); -}

Upload and download of. NET Core Files

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.