How to upload a file to ASP.Net Web API

Here is s simple function that takes a file upload and there can be other fields in the body that it will read.


        [HttpPost, Route("api/Action/UploadAFile")] 
        public async Task UploadAFile()
        {
            const string StoragePath = @"C:\Temp"; //pull from config file

            if (!Request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            } 
            var provider = new MultipartFormDataStreamProvider(StoragePath);

            try
            {
                await Request.Content.ReadAsMultipartAsync(provider); //saves it

                //now we want to rename it back to the name it had originally because the upload gives a  strange name of 'BodyPart_[Guid]'
                foreach (MultipartFileData fileData in provider.FileData)
                {
                    if (string.IsNullOrEmpty(fileData.Headers.ContentDisposition.FileName))
                    {
                        return BadRequest();
                    }
                    string fileName = fileData.Headers.ContentDisposition.FileName;
                    if (fileName.StartsWith("\"") && fileName.EndsWith("\""))
                    {
                        fileName = fileName.Trim('"');
                    }
                    if (fileName.Contains(@"/") || fileName.Contains(@"\"))
                    {
                        fileName = Path.GetFileName(fileName);
                    }

                    string newFileName = Path.Combine(StoragePath, fileName);

                    if (!File.Exists(newFileName))
                    {
                        File.Move(fileData.LocalFileName, newFileName);
                        //File.Move uses the Win32Native.MoveFile function, which does a rename on the file system
                    }
                    else
                    {
                        // a file by that name already exists, so delete the one that was just uploaded, and return an error message that fits 
                        // your standards
                        try
                        {
                            File.Delete(fileData.LocalFileName);
                        }
                        catch (Exception ex)
                        { 
                            //should log that the file delete for fileData.LocalFileName failed, so that someone could verify 
                            // it should have been deleted and they can feel ok about cleaning up this file later.
                            // Don't rethrow this error.
                        }

                        return BadRequest("File already exists.");
                    }


                }

                // Show all the key-value pairs.
                foreach (var key in provider.FormData.AllKeys)
                {
                    foreach (var val in provider.FormData.GetValues(key))
                    {
                        Trace.WriteLine(string.Format("{0}: {1}", key, val));
                        
                    }
                } 
                return Ok();
            }
            catch (System.Exception e)
            {
                return BadRequest();
            }
        }

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s