您好,登錄后才能下訂單哦!
今天就跟大家聊聊有關如何在Asp.Net中利用表單實現一個文件上傳功能,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結了以下內容,希望大家根據這篇文章可以有所收獲。
WebClient上傳只包含鍵值對的文本信息示例代碼:
WebClient上傳只包含文件的示例代碼:
對于既包含文件又包含文本鍵值對信息的示例代碼,需要構造表單提交的內容,對于學asp的同學來說,下面的表單提交內容一定不會陌生
所以只要拼一個這樣的byte[] data數據Post過去,就可以達到同樣的效果了。但是一定要注意,對于這種帶有文件上傳的,其ContentType是不一樣的,例如上面的這種,其ContentType為"multipart/form-data; boundary=---------------------------7d429871607fe"。有了ContentType,我們就可以知道boundary(就是上面的"---------------------------7d429871607fe"),知道boundary了我們就可以構造出我們所需要的byte[] data了,最后,不要忘記,把我們構造的ContentType傳到WebClient中(例如:webClient.Headers.Add("Content-Type", ContentType);)這樣,就可以通過WebClient.UploadData 方法上載文件數據了。
using System; using System.Web; using System.IO; using System.Net; using System.Text; using System.Collections; namespace UploadData.Common { public class CreateBytes { Encoding encoding = Encoding.UTF8; public byte[] JoinBytes(ArrayList byteArrays) { int length = 0; int readLength = 0; // 加上結束邊界 string endBoundary = Boundary + "-- "; byte[] endBoundaryBytes = encoding.GetBytes(endBoundary); byteArrays.Add(endBoundaryBytes); foreach (byte[] b in byteArrays) { length += b.Length; } byte[] bytes = new byte[length]; // 遍歷復制 foreach (byte[] b in byteArrays) { b.CopyTo(bytes, readLength); readLength += b.Length; } return bytes; } public bool UploadData(string uploadUrl, byte[] bytes, out byte[] responseBytes) { WebClient webClient = new WebClient(); webClient.Headers.Add("Content-Type", ContentType); try { responseBytes = webClient.UploadData(uploadUrl, bytes); return true; } catch (WebException ex) { Stream resp = ex.Response.GetResponseStream(); responseBytes = new byte[ex.Response.ContentLength]; resp.Read(responseBytes, 0, responseBytes.Length); } return false; } /// 獲取普通表單區域二進制數組 public byte[] CreateFieldData(string fieldName, string fieldValue) { string textTemplate = Boundary + " Content-Disposition: form-data; name="{0}" {1} "; string text = String.Format(textTemplate, fieldName, fieldValue); byte[] bytes = encoding.GetBytes(text); return bytes; } public byte[] CreateFieldData(string fieldName, string filename, string contentType, byte[] fileBytes) { string end = " "; string textTemplate = Boundary + " Content-Disposition: form-data; name="{0}"; filename="{1}" Content-Type: {2} "; // 頭數據 string data = String.Format(textTemplate, fieldName, filename, contentType); byte[] bytes = encoding.GetBytes(data); // 尾數據 byte[] endBytes = encoding.GetBytes(end); // 合成后的數組 byte[] fieldData = new byte[bytes.Length + fileBytes.Length + endBytes.Length]; bytes.CopyTo(fieldData, 0); // 頭數據 fileBytes.CopyTo(fieldData, bytes.Length); // 文件的二進制數據 endBytes.CopyTo(fieldData, bytes.Length + fileBytes.Length); // return fieldData; } public string Boundary { get { string[] bArray, ctArray; string contentType = ContentType; ctArray = contentType.Split(';'); if (ctArray[0].Trim().ToLower() == "multipart/form-data") { bArray = ctArray[1].Split('='); return "--" + bArray[1]; } return null; } } public string ContentType { get { if (HttpContext.Current == null) { return "multipart/form-data; boundary=---------------------------7d5b915500cee"; } return HttpContext.Current.Request.ContentType; } } } } using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; using UploadData.Common; using System.IO; namespace UploadDataWin { public class frmUpload : System.Windows.Forms.Form { private System.Windows.Forms.Label lblAmigoToken; private System.Windows.Forms.TextBox txtAmigoToken; private System.Windows.Forms.Label lblFilename; private System.Windows.Forms.TextBox txtFilename; private System.Windows.Forms.Button btnBrowse; private System.Windows.Forms.TextBox txtFileData; private System.Windows.Forms.Label lblFileData; private System.Windows.Forms.Button btnUpload; private System.Windows.Forms.OpenFileDialog openFileDialog1; private System.Windows.Forms.TextBox txtResponse; private System.ComponentModel.Container components = null; public frmUpload() { InitializeComponent(); } protected override void Dispose(bool disposing) { if (disposing) { if (components != null) { components.Dispose(); } } base.Dispose(disposing); } private void InitializeComponent() { this.lblAmigoToken = new System.Windows.Forms.Label(); this.txtAmigoToken = new System.Windows.Forms.TextBox(); this.lblFilename = new System.Windows.Forms.Label(); this.txtFilename = new System.Windows.Forms.TextBox(); this.btnBrowse = new System.Windows.Forms.Button(); this.txtFileData = new System.Windows.Forms.TextBox(); this.lblFileData = new System.Windows.Forms.Label(); this.btnUpload = new System.Windows.Forms.Button(); this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog(); this.txtResponse = new System.Windows.Forms.TextBox(); this.SuspendLayout(); // // lblAmigoToken // this.lblAmigoToken.Location = new System.Drawing.Point(40, 48); this.lblAmigoToken.Name = "lblAmigoToken"; this.lblAmigoToken.Size = new System.Drawing.Size(72, 23); this.lblAmigoToken.TabIndex = 0; this.lblAmigoToken.Text = "AmigoToken"; // // txtAmigoToken // this.txtAmigoToken.Location = new System.Drawing.Point(120, 48); this.txtAmigoToken.Name = "txtAmigoToken"; this.txtAmigoToken.Size = new System.Drawing.Size(248, 21); this.txtAmigoToken.TabIndex = 1; this.txtAmigoToken.Text = ""; // // lblFilename // this.lblFilename.Location = new System.Drawing.Point(40, 96); this.lblFilename.Name = "lblFilename"; this.lblFilename.Size = new System.Drawing.Size(80, 23); this.lblFilename.TabIndex = 2; this.lblFilename.Text = "Filename"; // // txtFilename // this.txtFilename.Location = new System.Drawing.Point(120, 96); this.txtFilename.Name = "txtFilename"; this.txtFilename.Size = new System.Drawing.Size(248, 21); this.txtFilename.TabIndex = 3; this.txtFilename.Text = ""; // // btnBrowse // this.btnBrowse.Location = new System.Drawing.Point(296, 144); this.btnBrowse.Name = "btnBrowse"; this.btnBrowse.TabIndex = 4; this.btnBrowse.Text = "瀏覽"; this.btnBrowse.Click += new System.EventHandler(this.btnBrowse_Click); // // txtFileData // this.txtFileData.Location = new System.Drawing.Point(120, 144); this.txtFileData.Name = "txtFileData"; this.txtFileData.Size = new System.Drawing.Size(168, 21); this.txtFileData.TabIndex = 5; this.txtFileData.Text = ""; // // lblFileData // this.lblFileData.Location = new System.Drawing.Point(40, 144); this.lblFileData.Name = "lblFileData"; this.lblFileData.Size = new System.Drawing.Size(72, 23); this.lblFileData.TabIndex = 6; this.lblFileData.Text = "FileData"; // // btnUpload // this.btnUpload.Location = new System.Drawing.Point(48, 184); this.btnUpload.Name = "btnUpload"; this.btnUpload.TabIndex = 7; this.btnUpload.Text = "Upload"; this.btnUpload.Click += new System.EventHandler(this.btnUpload_Click); // // txtResponse // this.txtResponse.Location = new System.Drawing.Point(136, 184); this.txtResponse.Multiline = true; this.txtResponse.Name = "txtResponse"; this.txtResponse.Size = new System.Drawing.Size(248, 72); this.txtResponse.TabIndex = 8; this.txtResponse.Text = ""; // // frmUpload // this.AutoScaleBaseSize = new System.Drawing.Size(6, 14); this.ClientSize = new System.Drawing.Size(400, 269); this.Controls.Add(this.txtResponse); this.Controls.Add(this.btnUpload); this.Controls.Add(this.lblFileData); this.Controls.Add(this.txtFileData); this.Controls.Add(this.btnBrowse); this.Controls.Add(this.txtFilename); this.Controls.Add(this.lblFilename); this.Controls.Add(this.txtAmigoToken); this.Controls.Add(this.lblAmigoToken); this.Name = "frmUpload"; this.Text = "frmUpload"; this.ResumeLayout(false); } [STAThread] static void Main() { Application.Run(new frmUpload()); } private void btnUpload_Click(object sender, System.EventArgs e) { // 非空檢驗 if (txtAmigoToken.Text.Trim() == "" || txtFilename.Text == "" || txtFileData.Text.Trim() == "") { MessageBox.Show("Please fill data"); return; } // 所要上傳的文件路徑 string path = txtFileData.Text.Trim(); // 檢查文件是否存在 if (!File.Exists(path)) { MessageBox.Show("{0} does not exist!", path); return; } // 讀文件流 FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read); // 這部分需要完善 string ContentType = "application/octet-stream"; byte[] fileBytes = new byte[fs.Length]; fs.Read(fileBytes, 0, Convert.ToInt32(fs.Length)); // 生成需要上傳的二進制數組 CreateBytes cb = new CreateBytes(); // 所有表單數據 ArrayList bytesArray = new ArrayList(); // 普通表單 bytesArray.Add(cb.CreateFieldData("FileName", txtFilename.Text)); bytesArray.Add(cb.CreateFieldData("AmigoToken", txtAmigoToken.Text)); // 文件表單 bytesArray.Add(cb.CreateFieldData("FileData", path , ContentType, fileBytes)); // 合成所有表單并生成二進制數組 byte[] bytes = cb.JoinBytes(bytesArray); // 返回的內容 byte[] responseBytes; // 上傳到指定Url bool uploaded = cb.UploadData("http://localhost/UploadData/UploadAvatar.aspx", bytes, out responseBytes); // 將返回的內容輸出到文件 using (FileStream file = new FileStream(@"c: esponse.text", FileMode.Create, FileAccess.Write, FileShare.Read)) { file.Write(responseBytes, 0, responseBytes.Length); } txtResponse.Text = System.Text.Encoding.UTF8.GetString(responseBytes); } private void btnBrowse_Click(object sender, System.EventArgs e) { if (openFileDialog1.ShowDialog() == DialogResult.OK) { txtFileData.Text = openFileDialog1.FileName; } } } }
看完上述內容,你們對如何在Asp.Net中利用表單實現一個文件上傳功能有進一步的了解嗎?如果還想了解更多知識或者相關內容,請關注億速云行業資訊頻道,感謝大家的支持。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。