Windows Phone 8 and Windows 8 use HTTP POST Multipart/Form-Data to upload files to the server
To upload files to the server using HTTP POST multipart/form-data in Windows Phone 8 or Windows 8, you need to follow the following steps:
You have provided a code snippet that attempts to upload a file using HttpWebRequest. However, there are some issues in the code that need to be fixed:
var file = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(DBNAME);
This code gets the files from the package installation directory instead of from local storage. Should be changed to var file = await ApplicationData.Current.LocalFolder.GetFileAsync(DBNAME);
. var res = await HttpPost(Util.UPLOAD_BACKUP, fileBytes);
This code starts an asynchronous HTTP POST request, but it never waits for the result. res.Wait();
should be called to wait for the result. Here’s an example of how to modify your code to upload files using 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>
In Windows 8, you can use the HttpClient class to upload files using multipart/form-data. Here's an example of how to do it:
<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>
The above is the detailed content of How to Upload Files via HTTP POST Multipart/Form-Data in Windows Phone 8 and Windows 8?. For more information, please follow other related articles on the PHP Chinese website!