Upload image through form post

I'm trying to upload an image through a multipart/form-data post and I'm using the code below. I'm only going to be uploading .jpg images.

The problem is that the image that is saved is not a valid image and it can't be viewed. It's also 200 bytes larger than the file I'm uploading so I assume I'm missing something here?

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);
            }
        }
    }
}

Here's a simple form I'm using to post the image.

<form action="/api/postuploadfile" enctype="multipart/form-data" method="post">
    Upload Image:
    <input type="file" id="imagename" name="imagename" />
    <input type="submit" />
</form> 

Info about the image, before/after:
If I check the properties of the image I've uploaded then the Size on disk is the same as the original image, but the Size property is 200-205 bytes larger. That's always the case, no matter how large the image is I upload.

Here's part of the POST headers. I don't need to strip out the boundary part or anything?

Source
-----------------------------1944294225892 Content-Disposition: form-data;
name="imagename"; filename="small.jpg" Content-Type: image/jpeg

And some more headers...

Request Headers From Upload Stream
Content-Length  125661
Content-Type    multipart/form-data; boundary=---------------------------1944294225892

Actually you will need to parse the requestStream with some kind of multipart parser as discussed here in order to strip off the header:

  • Reading file input from a multipart/form-data POST,
  • Are there any multipart/form-data parser in C# - (NO ASP)
  • 链接地址: http://www.djcxy.com/p/13146.html

    上一篇: 散列相同的字符多次

    下一篇: 通过表单上传图片上传