使用 HTTP POST Multipart/Form-Data 在 Windows Phone 8 中正確上傳檔案到伺服器
在 Web 開發中,使用帶有 multipart/form-data 的 HTTP POST 將檔案上傳到伺服器是一項常見任務。本文將解決在 Windows Phone 8 應用程式中使用 HTTPWebRequest 上傳檔案時遇到的問題,並提供改進的解決方案。
Windows Phone 8 中的原始程式碼
最初的實作使用 HttpWebRequest 發送 multipart/form-data POST 請求。但是,程式碼錯誤地嘗試發送整個檔案而沒有附帶元資料。 Multipart/form-data 請求需要指定檔案邊界和必要的表單資料標頭。
Windows Phone 8 的改良解
為了解決這個問題,以下是修改後的程式碼:
<code class="language-csharp">async void MainPage_Loaded(object sender, RoutedEventArgs e) { var file = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(DBNAME); 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); } } string boundary = Guid.NewGuid().ToString(); HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("http://www.myserver.com/upload.php"); httpWebRequest.ContentType = "multipart/form-data; boundary=" + boundary; httpWebRequest.Method = "POST"; httpWebRequest.BeginGetRequestStream(GetRequestStreamCallback, new object[] { fileBytes, boundary }); } private void GetRequestStreamCallback(IAsyncResult asynchronousResult, object state) { object[] stateData = (object[])state; byte[] postData = (byte[])stateData[0]; string boundary = (string)stateData[1]; HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState; Stream postStream = request.EndGetRequestStream(asynchronousResult); //写入起始边界 byte[] boundaryBytes = System.Text.Encoding.UTF8.GetBytes("--" + boundary + "\r\n"); postStream.Write(boundaryBytes, 0, boundaryBytes.Length); //写入文件数据 string filename = DBNAME; byte[] fileData = System.Text.Encoding.UTF8.GetBytes($"Content-Disposition: form-data; name=\"file\"; filename=\"{filename}\"\r\nContent-Type: application/octet-stream\r\n\r\n"); postStream.Write(fileData, 0, fileData.Length); postStream.Write(postData, 0, postData.Length); //写入结束边界 boundaryBytes = System.Text.Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n"); postStream.Write(boundaryBytes, 0, boundaryBytes.Length); postStream.Close(); request.BeginGetResponse(GetResponseCallback, request); } private void GetResponseCallback(IAsyncResult asynchronousResult) { HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState; using (HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult)) using (Stream streamResponse = response.GetResponseStream()) using (StreamReader streamRead = new StreamReader(streamResponse)) { string responseString = streamRead.ReadToEnd(); // 处理服务器响应 } }</code>
結論
此修改後的程式碼應解決 Windows Phone 8 應用程式中檔案上傳的問題。請記住,在使用 multipart/form-data 請求時,請務必正確指定邊界並為檔案和隨附的元資料提供必要的標頭。 程式碼中加入了更清晰的Content-Disposition頭,並使用了using語句來確保資源的正確釋放。
以上是如何在 Windows Phone 8 中使用 HTTP POST Multipart/Form-Data 正確地將檔案上傳到伺服器?的詳細內容。更多資訊請關注PHP中文網其他相關文章!