10

I have the bellow code which I have seen in other threads here, but nowhere does it actually show how to save a MultipartFileData file to disk once you have it.

[HttpPost]
public Task<HttpResponseMessage> PostFormData()
{
    // Check if the request contains multipart/form-data.
    if (!Request.Content.IsMimeMultipartContent())
    {
        throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
    }

    string root = HttpContext.Current.Server.MapPath(Settings.AssetImageTempStorage);
    var provider = new MultipartFormDataStreamProvider(root);

    // Read the form data and return an async task.
    var task = Request.Content.ReadAsMultipartAsync(provider).
        ContinueWith<HttpResponseMessage>(t =>
        {
            if (t.IsFaulted || t.IsCanceled)
            {
                Request.CreateErrorResponse(HttpStatusCode.InternalServerError, t.Exception);
            }

            // This illustrates how to get the file names.
            foreach (MultipartFileData file in provider.FileData)
            {
                // HOW DO I SAVE THIS FILE TO DISK HERE ???
                Trace.WriteLine(file.Headers.ContentDisposition.FileName);
                Trace.WriteLine("Server file path: " + file.LocalFileName);
            }
            return Request.CreateResponse(HttpStatusCode.OK);
        });

    return task;
}
ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
  • 1
    Did you looked at [this](http://stackoverflow.com/q/13732766/3032720) question? There is a line `File.Copy(fileData.LocalFileName, Path.Combine(StoragePath, fileName));` which, I think, copies received file to specific location. – mozgow Dec 03 '13 at 19:48
  • Thanks mozgow, I got it working in a similar way. now working fine, but in IE8 and IE9 I am getting Response : HTTP/1.1 415 Unsupported Media Type. In IE10 is fine but lower than that I get this silly error, and not sure why at all. –  Dec 04 '13 at 11:58
  • Sorry, found the issue. I was using blueimp http://blueimp.github.io/jQuery-File-Upload/basic.html File uploader. It ships with an iframe JS file for older browsers, which I did not include. I have included it now and it works fine. –  Dec 04 '13 at 12:40
  • 1
    user2520440 is long gone but the question in the code.. "HOW DO I SAVE THIS FILE TO DISK HERE ???" has a simple answer: You Don't Need To. It has already been saved at .ReadAsMultipartAsync(), this is what triggers the saving. – joedotnot Mar 24 '19 at 14:00

1 Answers1

26

Here is the sample for saving file in server. Hope this will help you.

public class TestController : ApiController
{
    const string StoragePath = @"T:\WebApiTest";
    public async Task<HttpResponseMessage> Post()
    {
        if (Request.Content.IsMimeMultipartContent())
        {
            var streamProvider = new MultipartFormDataStreamProvider(Path.Combine(StoragePath, "Upload"));
            await Request.Content.ReadAsMultipartAsync(streamProvider);
            foreach (MultipartFileData fileData in streamProvider.FileData)
            {
                if (string.IsNullOrEmpty(fileData.Headers.ContentDisposition.FileName))
                {
                    return Request.CreateResponse(HttpStatusCode.NotAcceptable, "This request is not properly formatted");
                }
                string fileName = fileData.Headers.ContentDisposition.FileName;
                if (fileName.StartsWith("\"") && fileName.EndsWith("\""))
                {
                    fileName = fileName.Trim('"');
                }
                if (fileName.Contains(@"/") || fileName.Contains(@"\"))
                {
                    fileName = Path.GetFileName(fileName);
                }
                File.Move(fileData.LocalFileName, Path.Combine(StoragePath, fileName));
            }
        }
        return Request.CreateResponse(HttpStatusCode.OK);
    }
    else
    {
        return Request.CreateResponse(HttpStatusCode.NotAcceptable, "This request is not properly formatted");
    }
}
G-Wiz
  • 7,370
  • 1
  • 36
  • 47
Abhilash Augustine
  • 4,128
  • 1
  • 24
  • 24
  • 3
    I'm having trouble with `File.Move(fileData.LocalFileName, Path.Combine(StoragePath, fileName));` occasionally getting "File in use" exception. – enorl76 Jul 06 '15 at 14:11
  • 1
    @enorl76 Sorry for the late reply. I think there should not get the exception of "File in use". But, if you got this exception you can try File.Copy() instead of File.Move(). Because, method File.Copy() will be executed even the source file is in use by another process. **System.IO.File.Copy(@"E:\asd.txt", @"F:\asd_copy.txt", true);** – Abhilash Augustine Jul 21 '15 at 05:57
  • Where can I find how to upload the data in the client side (.NET)? – Shimmy Weitzhandler Dec 10 '17 at 09:20
  • @Shimmy Sorry, I didn't get your question? – Abhilash Augustine Dec 12 '17 at 08:54
  • @AbhilashPA-Pullelil 1. Your code shows the server side code, I was rather looking for the server side code. 2. Is the file uploaded via streaming? – Shimmy Weitzhandler Dec 12 '17 at 09:45
  • Yep. I'm doubting between the variety of the options, which of them is the fastest... I can send `ByteArrayContent`, `StreamContent`, `PushStreamContent`, or inside a multipart with an attachment disposition. – Shimmy Weitzhandler Dec 12 '17 at 12:31
  • 1
    @Shimmy Oh, sorry. I am not in a position to answer this as I didn't tried any other types. If you can experiment it and share your valuable conclusions with us, it will be very helpful for all. – Abhilash Augustine Dec 13 '17 at 06:50