Windows Phone 8 和 Windows 8 使用 HTTP POST Multipart/Form-Data 上傳檔案到伺服器
在 Windows Phone 8 或 Windows 8 中使用 HTTP POST multipart/form-data 將檔案上傳到伺服器,需要遵循以下步驟:
您提供了一個嘗試使用 HttpWebRequest 上傳檔案的程式碼片段。但是,程式碼中有一些問題需要修復:
var file = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(DBNAME);
這段程式碼從套件安裝目錄取得文件,而不是從本機儲存取得。應改為 var file = await ApplicationData.Current.LocalFolder.GetFileAsync(DBNAME);
。 var res = await HttpPost(Util.UPLOAD_BACKUP, fileBytes);
這段程式碼啟動了一個非同步 HTTP POST 請求,但它從未等待結果。應呼叫 res.Wait();
來等待結果。 以下是如何修改程式碼以使用 multipart/form-data 上傳檔案的範例:
<code class="language-csharp">//假设您还有一个名为“userid”的字符串变量,其中包含用户 ID private async void HttpPost(byte[] fileBytes) { HttpClient httpClient = new HttpClient(); MultipartFormDataContent multipartContent = new MultipartFormDataContent(); HttpContent fileContent = new ByteArrayContent(fileBytes); multipartContent.Add(fileContent, "file", "filename.db"); multipartContent.Add(new StringContent(userid), "userid", "userdata.txt"); var response = await httpClient.PostAsync("http://www.myserver.com/upload.php", multipartContent); // ... }</code>
在 Windows 8 中,您可以使用 HttpClient 類別使用 multipart/form-data 上傳檔案。以下是如何操作的範例:
<code class="language-csharp">//假设您还有一个名为“userid”的字符串变量,其中包含用户 ID public async Task Upload(byte[] fileBytes) { using (HttpClient httpClient = new HttpClient()) { using (MultipartFormDataContent form = new MultipartFormDataContent()) { form.Add(new StringContent(username), "username"); form.Add(new StringContent(useremail), "email"); form.Add(new StringContent(password), "password"); form.Add(new ByteArrayContent(fileBytes, 0, fileBytes.Length), "profile_pic", "hello1.jpg"); HttpResponseMessage response = await httpClient.PostAsync("http://www.myserver.com/upload.php", form); // ... } } }</code>
以上是如何在 Windows Phone 8 和 Windows 8 中透過 HTTP POST Multipart/Form-Data 上傳檔案?的詳細內容。更多資訊請關注PHP中文網其他相關文章!