Skip to main content
 首页 » 编程设计

python之通过 POST multipart/form-data 从 windows phone 8.1 Silverlight Httpclient 上传文件到 python 服务器损坏文件

2025年05月04日9mate10pro

最初,我使用的是 Windows Phone 8 System.Net.Http使用以下代码将图像从 SD 卡上传到 Python 服务器的库:

    private async void UploadFile() 
    { 
        try 
        { 
            // Make sure there is a picture selected 
            if (photoStream != null) 
            { 
                // initialize the client 
                // need to make sure the server accepts network IP-based 
                // requests.  
                // ensure correct IP and correct port address 
                var fileUploadUrl = @"http://IPAddress/"; 
                var client = new HttpClient(); 
 
                // Reset the photoStream position 
                // If you don't reset the position, the content lenght 
                // sent will be 0 
                photoStream.Position = 0; 
 
                // This is the postdata 
                MultipartFormDataContent content = new MultipartFormDataContent(); 
                content.Add(new StreamContent(photoStream), "fn", fileName); 
 
                // upload the file sending the form info and ensure a result. 
                // it will throw an exception if the service doesn't return  
                // a valid successful status code 
                await client.PostAsync(fileUploadUrl, content) 
                    .ContinueWith((postTask) => 
                    { 
                        postTask.Result.EnsureSuccessStatusCode(); 
                    }); 
            } 
 
            // Disable the Upload button 
            btnUpload.IsEnabled = false; 
 
            // reset the image control 
            DisplayImage.Source = null; 
        } 
        catch 
        { 
 
        } 
    } 

在服务器端,我使用了以下 python 代码来解码请求:

ctype, pdict = cgi.parse_header(self.headers['content-type']) 
data = cgi.parse_multipart(self.rfile, pdict) 

它一直有效,直到我从 Windows Phone 8 切换到 Windows Phone 8.1 Silverlight。自 System.Net.Http Windows Phone 8.1 Silverlight 不再支持该库,我使用了 Windows.Web.Http而不是修改代码:

    private async void UploadFile() 
    { 
        try 
        { 
            // Make sure there is a picture selected 
            if (file != null) 
            { 
                // initialize the client 
                // need to make sure the server accepts network IP-based 
                // requests.  
                // ensure correct IP and correct port address 
                var fileUploadUrl = new Uri(@"http://IPAddress/", UriKind.Absolute); 
                var client = new HttpClient(); 
 
                HttpMultipartFormDataContent content = new HttpMultipartFormDataContent(); 
                HttpStreamContent streamContent = new HttpStreamContent(photoStream); 
                content.Add(streamContent, "fn", fileName); 
 
                await client.PostAsync(fileUploadUrl, content); 
 
            } 
 
            // Disable the Upload button 
            btnUpload.IsEnabled = false; 
 
            // reset the image control 
            DisplayImage.Source = null; 
        } 
        catch 
        { 
 
        } 
    } 

服务器端不变。但是,现在上传的结果文件会定期插入额外的字节,类似于 '\r\n10000\r\n'。或 0D 0A 31 30 30 30 30 0D 0A .该文件似乎也以相同的额外字节模式开始和结束。在服务器上 pdict将边界映射到类似 xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx 的位置, 但这似乎与通过 System.Net.Http 上传文件时的行为相同. 我尝试在一个较小的文件上手动删除这些字节,这似乎确认该文件在其他方面是正确的。

为什么会出现这些额外的字节?这是 Python 服务器错误处理 POST 请求的问题吗?

请您参考如下方法:

当我遇到这个问题时,这是我的解决方案:

客户:

 public async Task UploadImage(byte[] image, string url) 
        { 
            Stream stream = new System.IO.MemoryStream(image); 
            HttpStreamContent streamContent = new HttpStreamContent(stream.AsInputStream()); 
 
            Uri resourceAddress = null; 
            Uri.TryCreate(url.Trim(), UriKind.Absolute, out resourceAddress); 
            Windows.Web.Http.HttpRequestMessage request = new Windows.Web.Http.HttpRequestMessage(Windows.Web.Http.HttpMethod.Post, resourceAddress); 
            request.Content = streamContent; 
 
            var httpClient = new Windows.Web.Http.HttpClient(); 
            var cts = new CancellationTokenSource(); 
            Windows.Web.Http.HttpResponseMessage response = await httpClient.SendRequestAsync(request).AsTask(cts.Token); 
        } 

Controller :

public async Task<HttpResponseMessage> Post() 
{ 
    Stream requestStream = await this.Request.Content.ReadAsStreamAsync(); 
    byte[] byteArray = null; 
    using (MemoryStream ms = new MemoryStream()) 
    { 
        await requestStream.CopyToAsync(ms); 
        byteArray = ms.ToArray(); 
    } 
    . 
    . 
    . 
    return Request.CreateResponse(HttpStatusCode.OK); 
}