Repository navigation
Expand file tree
/
Copy pathFileUploadController.cs
More file actions
68 lines (60 loc) · 2.7 KB
/
Copy pathFileUploadController.cs
File metadata and controls
68 lines (60 loc) · 2.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using System.IO;
using Microsoft.AspNetCore.Hosting;
using System;
using System.Linq;
using System.Text.Json;
using ASP.NET_Core.Models;
namespace ASP.NET_Core.Controllers {
public class FileUploadController : Controller {
protected IWebHostEnvironment _hostingEnvironment { get; set; }
public FileUploadController(IWebHostEnvironment env) {
_hostingEnvironment = env;
}
[HttpPost]
public IActionResult Upload(IFormFile uploadedFile, string chunkMetadata) {
var tempPath = Path.Combine(_hostingEnvironment.WebRootPath, "uploads");
var resultImageUrl = string.Empty;
try {
if (!string.IsNullOrEmpty(chunkMetadata)) {
var metaDataObject = JsonSerializer.Deserialize<ChunkMetadata>(chunkMetadata);
CheckFileExtensionValid(metaDataObject.FileName);
var tempFilePath = Path.Combine(tempPath, metaDataObject.FileGuid + ".tmp");
if (!Directory.Exists(tempPath))
Directory.CreateDirectory(tempPath);
AppendContentToFile(tempFilePath, uploadedFile);
if (metaDataObject.Index == (metaDataObject.TotalCount - 1))
resultImageUrl = ProcessUploadedFile(tempFilePath, metaDataObject.FileName);
}
} catch {
return BadRequest();
}
return new JsonResult(new { imgUrl = resultImageUrl });
}
void CheckFileExtensionValid(string fileName) {
fileName = fileName.ToLower();
string[] imageExtensions = { ".jpg", ".jpeg", ".gif", ".png" };
var isValidExtenstion = imageExtensions.Any(ext => {
return fileName.LastIndexOf(ext) > -1;
});
if (!isValidExtenstion)
throw new Exception("Not allowed file extension");
}
void CheckMaxFileSize(FileStream stream) {
if (stream.Length > 4000000)
throw new Exception("File is too large");
}
string ProcessUploadedFile(string tempFilePath, string fileName) {
var path = Path.Combine(_hostingEnvironment.WebRootPath, "uploads", fileName);
System.IO.File.Copy(tempFilePath, path);
return Path.GetRelativePath(_hostingEnvironment.WebRootPath, path);
}
void AppendContentToFile(string path, IFormFile content) {
using (var stream = new FileStream(path, FileMode.Append, FileAccess.Write)) {
content.CopyTo(stream);
CheckMaxFileSize(stream);
}
}
}
}