0
votes

My client app will be sending me an image file and a video file through Multi part form data stream. And i want to store the image file in image folder and the video file in the video folder.

This is how the request from the client looks like

Content-Disposition: form-data; name="Photo"; filename="IMG_9322.JPG" Content-Type:application/octet-stream

Content-Disposition: form-data; name="Video"; filename="sample.avi" Content-Type:application/octet-stream

And this is the Api controller method at my end

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

        var folderName = "photos";
        string root = HttpContext.Current.Server.MapPath("~/" + folderName);
        var provider = new MultipartFormDataStreamProvider(root);

        try
        {               

            // Read the form data and return an async task.
            var response = await Request.Content.ReadAsMultipartAsync(provider);              


            return Request.CreateResponse(HttpStatusCode.OK, new ResponseMessage<Object> { success = true, message = "Media Uploaded" });

        }
        catch (System.Exception e)
        {
            return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
        }
    }

This stores both the files in the photo folder because thats the path i have given. But i dont know how i can separate both the files and store them in different paths. Please let me know if anyone has any idea? Thanks

1

1 Answers

0
votes

Look at the examples on the following page:

http://www.asp.net/web-api/overview/working-with-http/sending-html-form-data,-part-2

You want to get the file names after the files are downloaded and move them. I have done something very similar. Once you have the filename you can use

File.Move(currentPath,newPath)

to move the file to the new location. Your currentPath is your root variable plus the filename. Don't forget to add the @"\" as such:

currentPath = root + @"\" + filename

Below is code for getting the file name.

foreach (MultipartFileData file in provider.FileData)
{
    Trace.WriteLine(file.Headers.ContentDisposition.FileName);
    Trace.WriteLine("Server file path: " + file.LocalFileName);
}

My own first step would be to test the filename to determine the extension and then perform whatever action you want, in this case a move, once you find the appropriate file.