Asp. NET file Upload Upload Implementation method _ Practical skills

Source: Internet
Author: User
Tags datetime getdate httpcontext tojson hosting

This example for you to share the ASP.net file upload, for your reference, the specific contents are as follows

1, the recent project development needs to implement the attachment of asynchronous upload and download.

2, Upload: File uploaded to the specified path, and return the information uploaded to the front-end interface, such as: file icon, upload file name, file size.

3, upload, in front of the interface to display uploaded file information, click the file name implementation will upload the file download to the local.

4, first show the results of the demo operation chart:

After clicking Submit:

Click on file name to download to Local:

5, the following will give the foreground code:

<! DOCTYPE html>  

6, background upload code:

NameValueCollection NVF = HttpContext.Current.Request.Form; if (!
  Request.Content.IsMimeMultipartContent ()) {throw new httpresponseexception (Httpstatuscode.unsupportedmediatype);
  String TempPath = "/upload/" + DateTime.Now.ToString ("yyyy-mm-dd/"); String filesavelocation = HttpContext.Current.Server.MapPath ("~" + TempPath);//Attachment Save address Dictionary<string, Object
  > dic = new dictionary<string, object> (); if (!
  Directory.Exists (filesavelocation)) {directory.createdirectory (filesavelocation);
  } Custommultipartformdatastreamprovider Provider = new Custommultipartformdatastreamprovider (filesavelocation); try {var result = await Request.Content.ReadAsMultipartAsync (provider). Continuewith<dictionary<string, object>> (x => {var file = provider.
   FILEDATA[0]; FileInfo FileInfo = new FileInfo (file.
   LocalFilename); if (FileInfo. Length <= 0) {dic.
   ADD ("Result",-1); Dic.
   ADD ("Resultdetail", "not uploaded file"); } else {doUble? Filelength = FileInfo.
   length/1024.0; if (filelength > * 1024) {dic.
    ADD ("Result",-1); Dic.
   ADD ("Resultdetail", "Upload file can not be greater than 10M"); else {string savefilename = Guid.NewGuid (). ToString () + FileInfo.
    Extension; FileInfo.
    CopyTo (Path.Combine (filesavelocation, Savefilename), true); FileInfo.
    Delete (); Dic.
    ADD ("Result", 1); Dic.
    ADD ("Resultdetail", "upload success"); Dic. ADD ("Realpath", file. LocalFilename);//Attachments saved absolute path DIC. ADD ("Attachmenttype", FileInfo. Extension);//attachment type DIC. ADD ("AttachmentName", Path.getfilename (file). LocalFilename));//upload the attachment name dic. ADD ("Attachsize", Convert.ToInt32 (Filelength));//Attachment size KB dic.
  ADD ("Aealpath", TempPath + savefilename);//Attachment Save relative Path}} return dic;
  }, Taskscheduler.fromcurrentsynchronizationcontext ()); The catch (Exception ex) {return Handlejson.tojson (ex).
  ToString (), false); var issuccess = dic["Result".
  Trytoint () = = 1; var msg = dic["Resultdetail"]. Trytostring ()//return upload information var reaLpath = string. empty;//attachment saved absolute path var relativepath = string. empty;//returns the relative path var attachsize = 0;//File size kb var Attachmenttype = string. empty;//file name extension var attachmentname = string. empty;//the original filename if (issuccess) {Realpath = dic["Realpath"].
  Trytostring (); RelativePath = dic["Aealpath"].
  Trytostring (); Attachsize = dic["Attachsize"].
  Trytoint (); Attachmenttype = dic["Attachmenttype"].
  Trytostring (); AttachmentName = dic["AttachmentName"].
  Trytostring ();
  } StringBuilder sql = new StringBuilder (); if (issuccess) {try {#region gets the icon path var Icopath = string.
   Empty; Sql. Append (@ "SELECT * FROM dbo.")
   Attachmenttype (NOLOCK) WHERE attachmenttype= @AttachmentType "); var icotable = Common.HandleSQL.GetData (sql.
   ToString (), NULL, new sqlparameter[] {new SqlParameter ("@AttachmentType", Attachmenttype)});
   if (ICOTable.Rows.Count <= 0) {Icopath = ""; else {Icopath = icotable.rows[0]["Attachmentnametypeico"].
   ToString (); #endregion Get icon Path

   #region Save upload Log sql.
   Clear (); Sql. Append (@ "DECLARE @ID INT SELECT @ID =max (ID) +1 from dbo. Attachment (NOLOCK) IF (@ID is NULL) BEGIN SET @ID =1 end inserts into dbo. Attachment (ID, AttachmentName, Attachmenttype, Realpath, Attachsize, Uploaddate, Uploadperson, UpL Oadipaddress VALUES (@ID,--Id-int @AttachmentName,--Attachmentname-nvarchar (max) @AttachmentType,--at  Tachmenttype-nvarchar @RealPath--Realpath-nvarchar (max) @AttachSize--Attachsize-bigint GETDATE (), --Uploaddate-datetime @UpLoadPerson,--Uploadperson-nvarchar @UpLoadIPAddress--Uploadipaddress-varchar (m) SELECT * FROM dbo.
Attachment (NOLOCK) WHERE id= @ID;
   "); Sqlparameter[] paras = new sqlparameter[] {new SqlParameter ("@AttachmentName", AttachmentName), New SqlParameter ("@Att Achsize ", attachsize), New SqlParameter (" @RealPath ", RelativePath), New SqlParameter (" @AttachmentType ", Attachmenttype), New SqlParameter ("@UpLoadPerson"," Wei Xiaowei "), New SqlParameter (" @UpLoadIPAddress ", Handlelog.getipaddress ())}; var insert = GetData (sql.
   ToString (), NULL, paras); Insert.
   Columns.Add ("Attachmentnametypeico", typeof (String)); Insert.
   rows[0]["Attachmentnametypeico"] = Icopath; int ID = Convert.ToInt32 (insert. rows[0]["ID"].

   ToString ());//upload Attachment ID return handlejson.tojson (INSERT, 0);
   #endregion save upload Record} catch (Exception ex) {if (System.IO.File.Exists (Realpath)) {file.delete (Realpath); Return Handlejson.tojson (ex.
  ToString (), false);
  } else {return Handlejson.tojson (msg, FALSE);

 }

7, download code:

[HttpGet, Route ("Api/loding/download")] public httpresponsemessage DownLoad () {#region Get interface parameters NameValueCollection
  NVC = HttpContext.Current.Request.QueryString; int id = nvc["id"].
  Trytoint ();
  if (ID <= 0) {return Handlejson.tojson ("Incoming parameter error", false);
  #endregion Get interface Parameters #region SQL StringBuilder sql = new StringBuilder (); Sql. Append (@ "SELECT * FROM dbo.")

  Attachment (NOLOCK) WHERE id= @ID "); #endregion SQL #region Execute SQL var dt = Handlesql.getdata SQL.
  ToString (), NULL, new sqlparameter[] {new SqlParameter ("@ID", ID)}); if (dt.
  Rows.Count <= 0) {return Handlejson.tojson ("No download file found", false); } var FilePath = HttpContext.Current.Server.MapPath ("~" + dt.) rows[0]["Realpath"]. Trytostring ());//Download the absolute path of the file string fileName = dt. rows[0]["AttachmentName"]. Trytostring ();//download filename #endregion Execute SQL #region download file and add download record try {//var FilePath = System.Web.Hosting.Hosting
  Environment.mappath (@ "~/download/" + fileName); var stream = new FilestreAM (FilePath, FileMode.Open);
  Httpresponsemessage response = new Httpresponsemessage (Httpstatuscode.ok); Response.
  Content = new Streamcontent (stream); Response.
  Content.Headers.ContentType = new Mediatypeheadervalue ("Application/octet-stream"); Response.

  Content.Headers.ContentDisposition = new Contentdispositionheadervalue ("attachment") {filename = filename}; #region add download Record sql.
  Clear (); Sqlparameter[] paras = new sqlparameter[] {new SqlParameter ("@ID", ID), New SqlParameter ("@DownLoadPerson", "Wei Xiaowei"), New S
  Qlparameter ("@DownLoadIP", Handlelog.getipaddress ())}; Sql. Append (@ "DECLARE @AutoID INT SELECT @AutoID =max (autoid) +1 from dbo. Attachmentdowloadlog (NOLOCK) IF (@AutoID is NULL) BEGIN SET @AutoID =1 end inserts into dbo.  Attachmentdowloadlog (Autoid, ID, Downloadperson, Downloaddate, Downloadip) VALUES (@AutoID,--autoid-
  int @ID,--Id-int @DownLoadPerson,--Downloadperson-nvarchar (max) GETDATE (),--Downloaddate-datetime @DoWnloadip-Downloadip-nvarchar (50)); Execsql (SQL.

  ToString (), NULL, paras);
  #endregion Add download record return response;
  Catch {return new httpresponsemessage (httpstatuscode.nocontent);


 #endregion download files and add download records}

8, the above is only a small demo of my own, there is no or need to improve the place also please ask us a lot!

Wonderful topic sharing: ASP.net file upload summary

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Related Article

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.