我正在尝试通过 multipart/form-data
帖子上传图片,我正在使用下面的代码。我只会上传 .jpg
图片。
问题是保存的图像不是有效图像,无法查看。它也比我正在上传的文件大 200 个字节,所以我想我在这里遗漏了什么?
public class FileUploadController : ApiController
{
public Task<HttpResponseMessage> PostUploadFile()
{
return UploadFileAsync().ContinueWith<HttpResponseMessage>((tsk) =>
{
HttpResponseMessage response = null;
if (tsk.IsCompleted)
{
response = new HttpResponseMessage(HttpStatusCode.Created);
}
else if (tsk.IsFaulted || tsk.IsCanceled)
{
response =
new HttpResponseMessage(HttpStatusCode.InternalServerError);
}
return response;
});
}
public Task UploadFileAsync()
{
return this.Request.Content.ReadAsStreamAsync().ContinueWith((tsk) =>
{ SaveToFile(tsk.Result); },
TaskContinuationOptions.OnlyOnRanToCompletion);
}
private void SaveToFile(Stream requestStream)
{
string path =
System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory);
using (FileStream targetStream =
File.Create(path + "/Uploads/" + DateTime.Now.ToFileTime() + ".jpg"))
{
using (requestStream)
{
requestStream.CopyTo(targetStream);
}
}
}
}
这是我用来发布图片的简单表单。
<form action="/api/postuploadfile" enctype="multipart/form-data" method="post">
Upload Image:
<input type="file" id="imagename" name="imagename" />
<input type="submit" />
</form>
关于图像的信息,之前/之后:
如果我检查已上传图像的属性,则磁盘大小 与原始图像相同,但大小 属性大 200-205 字节。无论我上传多大的图片,情况总是如此。
这是 POST header 的一部分。我不需要去除边界部分或任何东西?
Source
-----------------------------1944294225892 Content-Disposition: form-data;
name="imagename"; filename="small.jpg" Content-Type: image/jpeg
还有一些标题...
Request Headers From Upload Stream
Content-Length 125661
Content-Type multipart/form-data; boundary=---------------------------1944294225892
最佳答案
实际上,您需要使用此处讨论的某种多部分解析器 来解析requestStream
,以便去除 header :
关于c# - 通过表单发布上传图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16414047/