Methods for uploading file data using the Webclient.uploaddata method _ Practical Tips

Source: Internet
Author: User
Tags httpcontext
If a website has a form, for example (url:http://localhost/login.aspx):
Account
Password

We need to submit data to this form in the program, for this form, we can use the Webclient.uploaddata method to achieve, the data to be uploaded into a character, the program is simple:

String uristring = "Http://localhost/login.aspx";
Create a new WebClient instance.
WebClient mywebclient = new WebClient ();
String postdata = "Username=admin&password=admin";
Note the contenttype of this spelling string
MYWEBCLIENT.HEADERS.ADD ("Content-type", "application/x-www-form-urlencoded");
Convert into binary array
byte[] ByteArray = Encoding.ASCII.GetBytes (postdata);
Upload the data and get the binary data returned.
byte[] Responsearray = Mywebclient.uploaddata (uristring, "POST", ByteArray);


For a File Upload class form, for example (url:http://localhost/uploadfile.aspx):
File

For this form, we can use
String uristring = "http://localhost/uploadFile.aspx";

Create a new WebClient instance.
WebClient mywebclient = new WebClient ();

String fileName = @ "C:upload.txt";

Upload directly, and get the binary data returned.
byte[] Responsearray = Mywebclient.uploadfile (uristring, "POST", fileName);


There is also a form that has not only text, but also files, such as (url:http://localhost/uploaddata.aspx):
Filename
File

For this form, it seems that the previous two methods are not suitable for the first method, can not directly spell string, for the second, we can only transfer files, back to the first method, note the parameters:
Public byte[] Uploaddata (
String address,
String method,
Byte[] Data
);
In the first example, it is through the spelling string to get the byte[] Data parameter value, for this form is obviously not, in turn think, for uploaddata.aspx such a program, directly through the Web page submission data, background to get the flow is what? (In my previous blog, has analyzed this problem: ASP no component upload progress bar solution), the final data is as follows:

-----------------------------7d429871607fe
Content-disposition:form-data; Name= "File1"; Filename= "G:homepage.txt"
Content-type:text/plain
Baoyu: Http://www.webuc.net
-----------------------------7d429871607fe
Content-disposition:form-data; Name= "FileName"
Default filename
-----------------------------7d429871607fe--


So as long as one such byte[] data post the past, you can achieve the same effect. However, it must be noted that for this file upload, its contenttype is not the same, such as the above, its contenttype as "MULTIPART/FORM-DATA;" boundary=---------------------------7d429871607fe ". With contenttype, we can know boundary (the "---------------------------7d429871607fe" above), knowing boundary we can construct the byte[we need. Data, and, finally, don't forget to pass our constructed ContentType to WebClient (for example: WebClient.Headers.Add ("Content-type", ContentType); You can upload file data through the Webclient.uploaddata method.

The specific code is as follows:
To generate a wrapper for a binary data class

Using System;
Using System.Web;
Using System.IO;
Using System.Net;
Using System.Text;
Using System.Collections;

Namespace Uploaddata.common
... {
/**////<summary>
To create a binary array for the Webclient.uploaddata method
</summary>
public class Createbytes
... {
Encoding Encoding = Encoding.UTF8;

/**////<summary>
Concatenation of all binary arrays into an array
</summary>
<param name= "bytearrays" > Array </param>
<returns></returns>
<remarks> Plus end Border </remarks>
Public byte[] Joinbytes (ArrayList bytearrays)
... {
int length = 0;
int readlength = 0;

Plus end boundary
String endboundary = boundary + "--rn"; End border
byte[] endboundarybytes = encoding. GetBytes (endboundary);
Bytearrays.add (endboundarybytes);

foreach (byte[] b in Bytearrays)
... {
length + = B.length;
}
byte[] bytes = new Byte[length];

Traverse replication
//
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;
}



/**////<summary>
Get a normal form region binary array
</summary>
<param name= "fieldName" > Table Single-name </param>
<param name= "Fieldvalue" > Form value </param>
<returns></returns>
<remarks>
-----------------------------7d52ee27210a3crncontent-disposition:form-data; Name= "Table Single-name" rnrn form value RN
</remarks>
Public byte[] Createfielddata (String fieldName, String fieldvalue)
... {
String texttemplate = boundary + "Rncontent-disposition:form-data;" Name= "{0}" RNRN{1}RN;
string text = String.Format (texttemplate, FieldName, Fieldvalue);
byte[] bytes = encoding. GetBytes (text);
return bytes;
}


/**////<summary>
Get File Upload form area binary array
</summary>
<param name= "fieldName" > Table Single-name </param>
<param name= "filename" > FileName </param>
<param name= "ContentType" > File type </param>
<param name= "contentlength" > File length </param>
<param name= "Stream" > File Flow </param>
<returns> binary Array </returns>
Public byte[] Createfielddata (String fieldName, String filename,string contentType, byte[] filebytes)
... {
String end = "RN";
String texttemplate = boundary + "Rncontent-disposition:form-data;" Name= "{0}"; Filename= "{1}" Rncontent-type: {2}rnrn;

Header data
String data = String.Format (texttemplate, fieldName, filename, contentType);
byte[] bytes = encoding. GetBytes (data);



Tail data
byte[] endbytes = encoding. GetBytes (end);

The synthesized array
byte[] Fielddata = new byte[bytes. Length + filebytes.length + endbytes.length];

bytes. CopyTo (fielddata, 0); Header data
Filebytes.copyto (Fielddata, bytes. Length); Binary data for files
Endbytes.copyto (Fielddata, bytes. Length + filebytes.length); Rn

return fielddata;
}


Property #region Property
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;
}
}
#endregion
}
}


Called in WinForm


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
... {
/**////<summary>
Summary description of the frmupload.
</summary>
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;
/**////<summary>
The required designer variable.
</summary>
Private System.ComponentModel.Container components = null;

Public Frmupload ()
... {
//
Required for Windows Forms Designer support
//
InitializeComponent ();

//
TODO: Add any constructor code after the InitializeComponent call
//
}

/**////<summary>
Clean up all resources that are in use.
</summary>
protected override void Dispose (bool disposing)
... {
if (disposing)
... {
if (Components!= null)
... {
Components. Dispose ();
}
}
Base. Dispose (disposing);
}

Windows Forms Designer generated Code #region the Windows Forms Designer generated code
/**////<summary>
Designer supports required methods-do not use the Code editor to modify
The contents of this method.
</summary>
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 = "browsing ...";
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);

}
#endregion

/**////<summary>
The main entry point for the application.
</summary>
[STAThread]
static void Main ()
... {
Application.Run (New Frmupload ());
}

private void Btnupload_click (object sender, System.EventArgs e)
... {
Non-null inspection
if (txtAmigoToken.Text.Trim () = = "" | | Txtfilename.text = "" | | TxtFileData.Text.Trim () = = "")
... {
MessageBox.Show ("Please fill data");
Return
}

The file path to upload
String path = TxtFileData.Text.Trim ();

Check to see if a file exists
if (! File.exists (PATH))
... {
MessageBox.Show ("{0} does not exist!", path);
Return
}

Read file stream
FileStream fs = new FileStream (path, FileMode.Open,
FileAccess.Read, FileShare.Read);

This part needs to be perfected
String ContentType = "Application/octet-stream";
byte[] filebytes = new Byte[fs. Length];
Fs. Read (filebytes, 0, Convert.ToInt32 (FS). Length));


Generating binary arrays that need to be uploaded
Createbytes cb = new Createbytes ();
All form data
ArrayList Bytesarray = new ArrayList ();
General form
Bytesarray.add (CB. Createfielddata ("FileName", Txtfilename.text));
Bytesarray.add (CB. Createfielddata ("Amigotoken", Txtamigotoken.text));
File Form
Bytesarray.add (CB. Createfielddata ("Filedata", Path
, ContentType, filebytes));

Synthesize all forms and generate binary arrays
byte[] bytes = cb. Joinbytes (Bytesarray);

What is returned
Byte[] responsebytes;

Upload to specified URL
BOOL uploaded = cb. Uploaddata ("http://localhost/UploadData/UploadAvatar.aspx", Bytes, out responsebytes);

Output the returned content to a file
using (FileStream file = new FileStream (@ "C:response.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;
}

}
}
}


The complete code is shown in attachment: Uploaddata.rar (38K) (http://bbs.openlab.net.cn/PostAttachment.aspx? postid=400927), after decompression to the web directory to build a virtual directory "Uploaddata", where uploadavatar.aspx is the actual upload processing page, if uploaded successfully, then return the file name and file type information. Default.aspx is the ASP.net page to invoke the Webclient.uploaddata method to submit the data, Uploaddatawin the project is the WinForm program call.

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.