C # simulate Form form upload file method

Source: Internet
Author: User

public static string UploadFile (string url, httppostedfilebase file,string FieldName)
{
Stream fs = file. InputStream;
if (!fs. CanRead)
{
Return "";
}
byte[] buffer = new BYTE[FS. Length];
Fs. Read (buffer, 0, (int) fs. Length);
Fs. Close ();

string boundary = "---------------------------" + DateTime.Now.Ticks.ToString ("x");
String PREFIX = "--", Line_end = "\ r \ n";

StringBuilder SB = new StringBuilder ();
SB. Append (PREFIX + boundary + line_end);
SB. Append ("Content-disposition:form-data; Name=\ "" + FieldName + "\"; Filename=\ "" + file. FileName + "\" "+ line_end);
SB. Append ("Content-type:" + file.) ContentType + line_end + line_end);
WebRequest request = webrequest.create (URL);
Request. Method = "POST";
Request. ContentType = "multipart/form-data;boundary=" + boundary;
Stream dataStream = Request. GetRequestStream ();
Datastream.write (Encoding.UTF8.GetBytes (sb. ToString ()), 0, Encoding.UTF8.GetByteCount (sb.) ToString ()));
Datastream.write (buffer, 0, buffer.) Length);
Datastream.write (Encoding.UTF8.GetBytes (line_end + PREFIX + boundary + PREFIX + line_end), 0, Encoding.UTF8.GetByteC Ount (line_end + PREFIX + boundary + PREFIX + line_end));
Datastream.close ();

WebResponse WebResponse = Request. GetResponse ();
Stream newstream = WebResponse.GetResponseStream ();

StreamReader RDR = new StreamReader (newstream);
var result = rdr. ReadToEnd ();
return result;
}

C # simulate Form form upload file method

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.