HttpClient StreamContent追加文件名两次

问题描述 投票:5回答:3

我正在使用Microsoft Http客户端库从Windows Phone 8向服务器发出多部分请求。它包含具有json字符串的String内容和具有图像流的Stream Content。现在我获得状态OK并请求服务器上的命中。但是日志说服务器无法获取图像的文件名。

content.Add(new StreamContent(photoStream), "files", fileName);

其中photoStream是图像流,“files”是内容的名称,文件名是图像文件的名称。

所以标头值必须是:

Content-Disposition: form-data; name=files; filename=image123.jpg

但实际上它是:

Content-Disposition: form-data; name=files; filename=image123.jpg; filename*=utf-8''image123.jpg

为什么它附加“; filename*=utf-8''image123.jpg”部分。这是一个问题吗?

请告诉我任何无法从WP8上传图片的原因/可能性。

c# windows-phone-8 content-type image-uploading multipartform-data
3个回答
11
投票
using (var content = new MultipartFormDataContent())
{
    content.Add(CreateFileContent(imageStream, fileName, "image/jpeg"));
}

private StreamContent CreateFileContent(Stream stream, string fileName, string contentType)
{
    var fileContent = new StreamContent(stream);
    fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data") 
    { 
        Name = "\"files\"", 
        FileName = "\"" + fileName + "\""
    };
    fileContent.Headers.ContentType = new MediaTypeHeaderValue(contentType);            
    return fileContent;
}

0
投票

对我来说,使用HttpStringContent而不是StreamContent,Damith的解决方案没有成功,但最后我找到了这个:

var fd = new Windows.Web.Http.HttpMultipartFormDataContent();
var file = new Windows.Web.Http.HttpStringContent(fs);
file.headers.contentType = new Windows.Web.Http.Headers.HttpMediaTypeHeaderValue("application/octet-stream");
fd.add(file);
file.headers.contentDisposition = new Windows.Web.Http.Headers.HttpContentDispositionHeaderValue.parse("form-data; name=\"your_form_name\"; filename=\"your_file_name\"");

注意:添加文件后设置内容处置是绝对必要的,否则标题将被“表单数据”覆盖。


-2
投票

我的简单方案:

HttpContent fileStreamContent = new StreamContent(new FileStream(xmlTmpFile, FileMode.Open));
var formData = new MultipartFormDataContent();
formData.Add(fileStreamContent, "xml", Path.GetFileName(xmlTmpFile));
fileStreamContent.Headers.ContentDisposition.FileNameStar = null;
© www.soinside.com 2019 - 2024. All rights reserved.