Advertisement
Guest User

Untitled

a guest
Apr 24th, 2019
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.11 KB | None | 0 0
  1. HttpPost("UploadFiles")]
  2.   [Produces("application/json")]
  3.   public async Task<IActionResult> Post(List<IFormFile> files)
  4.   {
  5.     // Get the file from the POST request
  6.     var theFile = HttpContext.Request.Form.Files.GetFile("file");
  7.  
  8.     // Get the server path, wwwroot
  9.     string webRootPath = _hostingEnvironment.WebRootPath;
  10.  
  11.     // Building the path to the uploads directory
  12.     var fileRoute = Path.Combine(webRootPath, "uploads");
  13.  
  14.     // Get the mime type
  15.     var mimeType = HttpContext.Request.Form.Files.GetFile("file").ContentType;
  16.  
  17.     // Get File Extension
  18.     string extension = System.IO.Path.GetExtension(theFile.FileName);
  19.  
  20.     // Generate Random name.
  21.     string name = Guid.NewGuid().ToString().Substring(0, 8) + extension;
  22.  
  23.     // Build the full path inclunding the file name
  24.     string link = Path.Combine(fileRoute, name);
  25.  
  26.     // Create directory if it does not exist.
  27.     FileInfo dir = new FileInfo(fileRoute);
  28.     dir.Directory.Create();
  29.  
  30.     // Basic validation on mime types and file extension
  31.     string[] imageMimetypes = { "image/gif", "image/jpeg", "image/pjpeg", "image/x-png", "image/png", "image/svg+xml" };
  32.     string[] imageExt = { ".gif", ".jpeg", ".jpg", ".png", ".svg", ".blob" };
  33.  
  34.     try
  35.     {
  36.       if (Array.IndexOf(imageMimetypes, mimeType) >= 0 && (Array.IndexOf(imageExt, extension) >= 0))
  37.       {
  38.         // Copy contents to memory stream.
  39.         Stream stream;
  40.         stream = new MemoryStream();
  41.         theFile.CopyTo(stream);
  42.         stream.Position = 0;
  43.         String serverPath = link;
  44.  
  45.         // Save the file
  46.         using (FileStream writerFileStream = System.IO.File.Create(serverPath))
  47.         {
  48.           await stream.CopyToAsync(writerFileStream);
  49.           writerFileStream.Dispose();
  50.         }
  51.  
  52.         // Return the file path as json
  53.         Hashtable imageUrl = new Hashtable();
  54.         imageUrl.Add("link", "/uploads/" + name);
  55.  
  56.         return Json(imageUrl);
  57.       }
  58.       throw new ArgumentException("The image did not pass the validation");
  59.     }
  60.  
  61.     catch (ArgumentException ex)
  62.     {
  63.       return Json(ex.Message);
  64.     }
  65.   }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement