Uploading a File to a Server Using HTTP POST Multipart/Form-Data in Windows Phone 8
You are attempting to upload an SQLite database to a PHP web service via an HTTP POST request with multipart/form-data MIME type and an additional string data "userid=SOME_ID." However, your current code is not working as expected.
The "multipart/form-data" MIME type enables the transmission of form data along with complex binary data such as files. It is widely used for file uploads in web applications.
To overcome the challenges encountered in your Windows Phone 8 code, consider using the following built-in functions:
Here is an improved version of your code:
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); } } HttpPost(fileBytes); } private async void HttpPost(byte[] fileBytes) { HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("http://www.myserver.com/upload.php"); httpWebRequest.ContentType = "multipart/form-data"; httpWebRequest.Method = "POST"; using (var formBody = new HttpFormBody()) { formBody.AddString("userid", HttpUtility.UrlEncode("SOME_ID")); httpWebRequest.AddString(formBody.CreateFormField()); } using (var dataStream = await httpWebRequest.GetRequestStreamAsync()) { dataStream.Write(fileBytes, 0, fileBytes.Length); dataStream.Close(); } var asyncResult = httpWebRequest.BeginGetResponse(new AsyncCallback(GetResponseCallback), httpWebRequest); }
This modification adds the "userid" string to the request body using the HttpRequest.AddString() method. It also ensures that the file bytes are appended to the end of the request body. By using these functions, you can effectively transmit both the file and the additional string data in the HTTP POST request, satisfying the multipart/form-data requirements.
The above is the detailed content of How to Upload a File and String Data Using HTTP POST Multipart/Form-Data in Windows Phone 8?. For more information, please follow other related articles on the PHP Chinese website!