Home > Backend Development > C++ > How to Correctly Upload Files to a Server using HTTP POST Multipart/Form-Data in Windows Phone 8?

How to Correctly Upload Files to a Server using HTTP POST Multipart/Form-Data in Windows Phone 8?

Linda Hamilton
Release: 2025-01-21 04:12:09
Original
196 people have browsed it

How to Correctly Upload Files to a Server using HTTP POST Multipart/Form-Data in Windows Phone 8?

Correctly upload files to server in Windows Phone 8 using HTTP POST Multipart/Form-Data

In web development, uploading files to the server using HTTP POST with multipart/form-data is a common task. This article will resolve issues encountered when using HTTPWebRequest to upload files in Windows Phone 8 apps and provide an improved solution.

Original code in Windows Phone 8

The original implementation uses HttpWebRequest to send multipart/form-data POST requests. However, the code incorrectly attempts to send the entire file without accompanying metadata. Multipart/form-data requests need to specify file boundaries and the necessary form data headers.

Improved solutions for Windows Phone 8

To solve this problem, the following is the modified code:

<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>
Copy after login

Conclusion

This modified code should resolve file upload issues in Windows Phone 8 apps. Remember, when using multipart/form-data requests, be sure to specify the boundaries correctly and provide the necessary headers for the file and accompanying metadata. A clearer Content-Disposition header has been added to the code, and using statements are used to ensure correct release of resources.

The above is the detailed content of How to Correctly Upload Files to a Server using HTTP POST Multipart/Form-Data in Windows Phone 8?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template