Created
October 6, 2016 08:37
-
-
Save mirsaeedi/ae6462906be7f6c8021abbc22ccef4e9 to your computer and use it in GitHub Desktop.
Helps you to save uploaded files to disk in ASP.Net Web API. The SaveFile method works with Request object directly.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public async Task<IHttpActionResult> SaveFile(string diskFolderPath) | |
{ | |
var path = Path.GetTempPath(); | |
if (!Request.Content.IsMimeMultipartContent("form-data")) | |
{ | |
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.UnsupportedMediaType)); | |
} | |
MultipartFormDataStreamProvider streamProvider = new MultipartFormDataStreamProvider(path); | |
await Request.Content.ReadAsMultipartAsync(streamProvider); | |
foreach (MultipartFileData fileData in streamProvider.FileData) | |
{ | |
string fileName = ""; | |
if (string.IsNullOrEmpty(fileData.Headers.ContentDisposition.FileName)) | |
{ | |
fileName = Guid.NewGuid().ToString(); | |
} | |
fileName = fileData.Headers.ContentDisposition.FileName; | |
if (fileName.StartsWith("\"") && fileName.EndsWith("\"")) | |
{ | |
fileName = fileName.Trim('"'); | |
} | |
if (fileName.Contains(@"/") || fileName.Contains(@"\")) | |
{ | |
fileName = Path.GetFileName(fileName); | |
} | |
var newFileName = Path.Combine(HostingEnvironment.MapPath("~" + diskFolderPath), fileName); | |
var fileInfo = new FileInfo(newFileName); | |
if (fileInfo.Exists) | |
{ | |
fileName = fileInfo.Name.Replace(fileInfo.Extension, ""); | |
fileName = fileName + (new Random().Next(0, 10000)) + fileInfo.Extension; | |
newFileName = Path.Combine(HostingEnvironment.MapPath(diskFolderPath), fileName); | |
} | |
if (!Directory.Exists(fileInfo.Directory.FullName)) | |
{ | |
Directory.CreateDirectory(fileInfo.Directory.FullName); | |
} | |
File.Move(fileData.LocalFileName, newFileName); | |
return Json(new { link = diskFolderPath + fileName }); | |
} | |
return BadRequest(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here I fixed some bugs like creating random filename and else statement