php post表单提交文件上传,如何使用HTTP POST multipart / form-data将文件上传到服务器?...

这是我最后的工作代码。我的Web服务需要一个文件(POST参数名称为“file”)和一个字符串值(POST参数名称为“userid”)。/// /// Occurs when upload backup application bar button is clicked. Author : Farhan Ghumra

/// private async void btnUploadBackup_Click(object sender, EventArgs e){

var dbFile = await ApplicationData.Current.LocalFolder.GetFileAsync(Util.DBNAME);

var fileBytes = await GetBytesAsync(dbFile);

var Params = new Dictionary { { "userid", "9" } };

UploadFilesToServer(new Uri(Util.UPLOAD_BACKUP), Params, Path.GetFileName(dbFile.Path), "application/octet-stream", fileBytes);}/// /// Creates HTTP POST request & uploads database to server. Author : Farhan Ghumra/// private void UploadFilesToServer(Uri uri, Dictionary data, string fileName, string fileContentType, byte[] fileData){

string boundary = "----------" + DateTime.Now.Ticks.ToString("x");

HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);

httpWebRequest.ContentType = "multipart/form-data; boundary=" + boundary;

httpWebRequest.Method = "POST";

httpWebRequest.BeginGetRequestStream((result) =>

{

try

{

HttpWebRequest request = (HttpWebRequest)result.AsyncState;

using (Stream requestStream = request.EndGetRequestStream(result))

{

WriteMultipartForm(requestStream, boundary, data, fileName, fileContentType, fileData);

}

request.BeginGetResponse(a =>

{

try

{

var response = request.EndGetResponse(a);

var responseStream = response.GetResponseStream();

using (var sr = new StreamReader(responseStream))

{

using (StreamReader streamReader = new StreamReader(response.GetResponseStream()))

{

string responseString = streamReader.ReadToEnd();

//responseString is depend upon your web service.

if (responseString == "Success")

{

MessageBox.Show("Backup stored successfully on server.");

}

else

{

MessageBox.Show("Error occurred while uploading backup on server.");

}

}

}

}

catch (Exception)

{

}

}, null);

}

catch (Exception)

{

}

}, httpWebRequest);}/// /// Writes multi part HTTP POST request. Author : Farhan Ghumra/// private void WriteMultipartForm(Stream s, string boundary, Dictionary data, string fileName, string fileContentType, byte[] fileData){

/// The first boundary

byte[] boundarybytes = Encoding.UTF8.GetBytes("--" + boundary + "\r\n");

/// the last boundary.

byte[] trailer = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");

/// the form data, properly formatted

string formdataTemplate = "Content-Dis-data; name=\"{0}\"\r\n\r\n{1}";

/// the form-data file upload, properly formatted

string fileheaderTemplate = "Content-Dis-data; name=\"{0}\"; filename=\"{1}\";\r\nContent-Type: {2}\r\n\r\n";

/// Added to track if we need a CRLF or not.

bool bNeedsCRLF = false;

if (data != null)

{

foreach (string key in data.Keys)

{

/// if we need to drop a CRLF, do that.

if (bNeedsCRLF)

WriteToStream(s, "\r\n");

/// Write the boundary.

WriteToStream(s, boundarybytes);

/// Write the key.

WriteToStream(s, string.Format(formdataTemplate, key, data[key]));

bNeedsCRLF = true;

}

}

/// If we don't have keys, we don't need a crlf.

if (bNeedsCRLF)

WriteToStream(s, "\r\n");

WriteToStream(s, boundarybytes);

WriteToStream(s, string.Format(fileheaderTemplate, "file", fileName, fileContentType));

/// Write the file data to the stream.

WriteToStream(s, fileData);

WriteToStream(s, trailer);}/// /// Writes string to stream. Author : Farhan Ghumra/// private void WriteToStream(Stream s, string txt){

byte[] bytes = Encoding.UTF8.GetBytes(txt);

s.Write(bytes, 0, bytes.Length);}/// /// Writes byte array to stream. Author : Farhan Ghumra/// private void WriteToStream(Stream s, byte[] bytes){

s.Write(bytes, 0, bytes.Length);}/// /// Returns byte array from StorageFile. Author : Farhan Ghumra/// private async Task GetBytesAsync(StorageFile file){

byte[] fileBytes = null;

using (var stream = await file.OpenReadAsync())

{

fileBytes = new byte[stream.Size];

using (var reader = new DataReader(stream))

{

await reader.LoadAsync((uint)stream.Size);

reader.ReadBytes(fileBytes);

}

}

return fileBytes;}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值