├── Controllers └── FileController.cs ├── LICENSE ├── Models └── FlowModels.cs ├── README.md ├── Repository ├── FlowJsRepo.cs └── IFlowJsRepo.cs ├── Scripts └── Upload.js └── Views └── Upload.cshtml /Controllers/FileController.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.Threading.Tasks; 5 | using System.Web; 6 | using System.Web.Http; 7 | using FlowJs; 8 | using FlowJs.Interface; 9 | using Microsoft.AspNet.Identity; 10 | 11 | namespace MyProject.Controllers 12 | { 13 | [Authorize] 14 | [RoutePrefix("api/File")] 15 | public class FileController : ApiController 16 | { 17 | private readonly IFileManagerService _fileManager; 18 | private readonly IFlowJsRepo _flowJs; 19 | 20 | public PictureController() 21 | { 22 | _fileManager = new FileManagerService(); 23 | _flowJs = new FlowJsRepo(); 24 | } 25 | 26 | const string Folder = @"C:\Temp\PicUpload"; 27 | 28 | [HttpGet] 29 | [Route("Upload")] 30 | public async Task PictureUploadGet() 31 | { 32 | var request = HttpContext.Current.Request; 33 | 34 | var chunkExists = _flowJs.ChunkExists(Folder, request); 35 | if (chunkExists) return Ok(); 36 | return ResponseMessage(new HttpResponseMessage(HttpStatusCode.NoContent)); 37 | } 38 | 39 | [HttpPost] 40 | [Route("Upload")] 41 | public async Task PictureUploadPost() 42 | { 43 | var request = HttpContext.Current.Request; 44 | 45 | var validationRules = new FlowValidationRules(); 46 | validationRules.AcceptedExtensions.AddRange(new List { "jpeg", "jpg", "png", "bmp" }); 47 | validationRules.MaxFileSize = 5000000; 48 | 49 | try 50 | { 51 | var status = _flowJs.PostChunk(request, Folder, validationRules); 52 | 53 | if (status.Status == PostChunkStatus.Done) 54 | { 55 | // file uploade is complete. Below is an example of further file handling 56 | var filePath = Path.Combine(Folder, status.FileName); 57 | var file = File.ReadAllBytes(filePath); 58 | var picture = await _fileManager.UploadPictureToS3(User.Identity.GetUserId(), file, status.FileName); 59 | File.Delete(filePath); 60 | return Ok(picture); 61 | } 62 | 63 | if (status.Status == PostChunkStatus.PartlyDone) 64 | { 65 | return Ok(); 66 | } 67 | 68 | status.ErrorMessages.ForEach(x => ModelState.AddModelError("file", x)); 69 | return BadRequest(ModelState); 70 | } 71 | catch (Exception) 72 | { 73 | ModelState.AddModelError("file", "exception"); 74 | return BadRequest(ModelState); 75 | } 76 | } 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 Dmitry A. Efimenko 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /Models/FlowModels.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Collections.Specialized; 4 | using System.Linq; 5 | using System.Text.RegularExpressions; 6 | 7 | namespace FlowJs 8 | { 9 | public enum PostChunkStatus 10 | { 11 | Error = 0, 12 | Done = 1, 13 | PartlyDone = 2 14 | } 15 | public class FlowJsPostChunkResponse 16 | { 17 | public FlowJsPostChunkResponse() 18 | { 19 | ErrorMessages = new List(); 20 | } 21 | 22 | public string FileName { get; set; } 23 | public long Size { get; set; } 24 | public PostChunkStatus Status { get; set; } 25 | public List ErrorMessages { get; set; } 26 | } 27 | 28 | public class FlowChunk 29 | { 30 | public int Number { get; set; } 31 | public long Size { get; set; } 32 | public long TotalSize { get; set; } 33 | public string Identifier { get; set; } 34 | public string FileName { get; set; } 35 | public int TotalChunks { get; set; } 36 | 37 | internal bool ParseForm(NameValueCollection form) 38 | { 39 | try 40 | { 41 | if (string.IsNullOrEmpty(form["flowIdentifier"]) || string.IsNullOrEmpty(form["flowFilename"])) 42 | return false; 43 | 44 | Number = int.Parse(form["flowChunkNumber"]); 45 | Size = long.Parse(form["flowChunkSize"]); 46 | TotalSize = long.Parse(form["flowTotalSize"]); 47 | Identifier = CleanIdentifier(form["flowIdentifier"]); 48 | FileName = form["flowFilename"]; 49 | TotalChunks = int.Parse(form["flowTotalChunks"]); 50 | } 51 | catch (Exception) 52 | { 53 | return false; 54 | } 55 | return true; 56 | } 57 | 58 | internal bool ValidateBusinessRules(FlowValidationRules rules, out List errorMessages) 59 | { 60 | errorMessages = new List(); 61 | if(rules.MaxFileSize.HasValue && TotalSize > rules.MaxFileSize.Value) 62 | errorMessages.Add(rules.MaxFileSizeMessage ?? "size"); 63 | 64 | if (rules.AcceptedExtensions.Count > 0 && rules.AcceptedExtensions.SingleOrDefault(x => x.ToLowerCase() == FileName.Split('.').Last().ToLowerCase()) == null) 65 | errorMessages.Add(rules.AcceptedExtensionsMessage ?? "type"); 66 | 67 | return errorMessages.Count == 0; 68 | } 69 | 70 | private string CleanIdentifier(string identifier) 71 | { 72 | identifier = Regex.Replace(identifier, "/[^0-9A-Za-z_-]/g", ""); 73 | return identifier; 74 | } 75 | 76 | 77 | 78 | } 79 | 80 | public class FlowValidationRules 81 | { 82 | public FlowValidationRules() 83 | { 84 | AcceptedExtensions = new List(); 85 | } 86 | 87 | public long? MaxFileSize { get; set; } 88 | public string MaxFileSizeMessage { get; set; } 89 | 90 | public List AcceptedExtensions { get; set; } 91 | public string AcceptedExtensionsMessage { get; set; } 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | FlowJs-MVC 2 | ================== 3 | 4 | Provides MVC handler for [FlowJs](https://github.com/flowjs) uploads 5 | 6 | Installation: 7 | ------------- 8 | Just add .cs files from folders "Models" and "Repository" to your project. 9 | 10 | Examples: 11 | ------------- 12 | The `FileController.cs`, `Upload.cshtml`, and `Upload.js` files are provided as examples. 13 | 14 | The code in the client side examples uses AngularJs and the following directives: 15 | * [ng-flow](https://github.com/flowjs/ng-flow) - AngularJs wrapper for flowJs 16 | * [ng-server-validation](https://github.com/DmitryEfimenko/ng-server-validation) - handling server side errors 17 | -------------------------------------------------------------------------------- /Repository/FlowJsRepo.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.Web; 5 | using FlowJs.Interface; 6 | 7 | namespace FlowJs 8 | { 9 | public class FlowJsRepo : IFlowJsRepo 10 | { 11 | public FlowJsPostChunkResponse PostChunk(HttpRequest request, string folder) 12 | { 13 | return PostChunkBase(request, folder, null); 14 | } 15 | 16 | public FlowJsPostChunkResponse PostChunk(HttpRequest request, string folder, FlowValidationRules validationRules) 17 | { 18 | return PostChunkBase(request, folder, validationRules); 19 | } 20 | 21 | public bool ChunkExists(string folder, HttpRequest request) 22 | { 23 | var identifier = request.QueryString["flowIdentifier"]; 24 | var chunkNumber = int.Parse(request.QueryString["flowChunkNumber"]); 25 | var chunkFullPathName = GetChunkFilename(chunkNumber, identifier, folder); 26 | return File.Exists(Path.Combine(folder, chunkFullPathName)); 27 | } 28 | 29 | private FlowJsPostChunkResponse PostChunkBase(HttpRequest request, string folder, FlowValidationRules validationRules) 30 | { 31 | var chunk = new FlowChunk(); 32 | var requestIsSane = chunk.ParseForm(request.Form); 33 | if (!requestIsSane) 34 | { 35 | var errResponse = new FlowJsPostChunkResponse(); 36 | errResponse.Status = PostChunkStatus.Error; 37 | errResponse.ErrorMessages.Add("damaged"); 38 | } 39 | 40 | List errorMessages = null; 41 | var file = request.Files[0]; 42 | 43 | var response = new FlowJsPostChunkResponse {FileName = chunk.FileName, Size = chunk.TotalSize}; 44 | 45 | var chunkIsValid = true; 46 | if(validationRules != null) 47 | chunkIsValid = chunk.ValidateBusinessRules(validationRules, out errorMessages); 48 | 49 | if (!chunkIsValid) 50 | { 51 | response.Status = PostChunkStatus.Error; 52 | response.ErrorMessages = errorMessages; 53 | return response; 54 | } 55 | 56 | var chunkFullPathName = GetChunkFilename(chunk.Number, chunk.Identifier, folder); 57 | try 58 | { 59 | // create folder if it does not exist 60 | if (!Directory.Exists(folder)) Directory.CreateDirectory(folder); 61 | // save file 62 | file.SaveAs(chunkFullPathName); 63 | } 64 | catch (Exception) 65 | { 66 | throw; 67 | } 68 | 69 | // see if we have more chunks to upload. If so, return here 70 | for (int i = 1, l = chunk.TotalChunks; i <= l; i++) 71 | { 72 | var chunkNameToTest = GetChunkFilename(i, chunk.Identifier, folder); 73 | var exists = File.Exists(chunkNameToTest); 74 | if (!exists) 75 | { 76 | response.Status = PostChunkStatus.PartlyDone; 77 | return response; 78 | } 79 | } 80 | 81 | // if we are here, all chunks are uploaded 82 | var fileAry = new List(); 83 | for (int i = 1, l = chunk.TotalChunks; i <= l; i++) 84 | { 85 | fileAry.Add("flow-" + chunk.Identifier + "." + i); 86 | } 87 | 88 | MultipleFilesToSingleFile(folder, fileAry, chunk.FileName); 89 | 90 | for (int i = 0, l = fileAry.Count; i < l; i++) 91 | { 92 | try 93 | { 94 | File.Delete(Path.Combine(folder, fileAry[i])); 95 | } 96 | catch (Exception) 97 | { 98 | } 99 | } 100 | 101 | response.Status = PostChunkStatus.Done; 102 | return response; 103 | 104 | } 105 | 106 | 107 | 108 | private static void MultipleFilesToSingleFile(string dirPath, IEnumerable fileAry, string destFile) 109 | { 110 | using (var destStream = File.Create(Path.Combine(dirPath, destFile))) 111 | { 112 | foreach (string filePath in fileAry) 113 | { 114 | using (var sourceStream = File.OpenRead(Path.Combine(dirPath, filePath))) 115 | sourceStream.CopyTo(destStream); // You can pass the buffer size as second argument. 116 | } 117 | } 118 | } 119 | 120 | private string GetChunkFilename(int chunkNumber, string identifier, string folder) 121 | { 122 | return Path.Combine(folder, "flow-" + identifier + "." + chunkNumber); 123 | } 124 | } 125 | } 126 | -------------------------------------------------------------------------------- /Repository/IFlowJsRepo.cs: -------------------------------------------------------------------------------- 1 | using System.Web; 2 | 3 | namespace FlowJs.Interface 4 | { 5 | public interface IFlowJsRepo 6 | { 7 | FlowJsPostChunkResponse PostChunk(HttpRequest request, string folder); 8 | FlowJsPostChunkResponse PostChunk(HttpRequest request, string folder, FlowValidationRules validationRules); 9 | bool ChunkExists(string folder, HttpRequest request); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /Scripts/Upload.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | angular.module('app.controllers').controller('PicUploadController', [ 4 | '$scope', 'miscService', function ($scope, miscService) { 5 | 6 | $scope.files = []; 7 | 8 | $scope.fileUploadSuccess = function (message) { 9 | $scope.files.push(JSON.parse(message)); 10 | }; 11 | 12 | $scope.fileUploadProgress = function (progress) { 13 | $scope.fileProgress = Math.round(progress * 100); 14 | }; 15 | 16 | $scope.uploadError = function (message) { 17 | var jsonResponse = JSON.parse(message); 18 | var modelState = jsonResponse.modelState; 19 | $scope.modelState = modelState; 20 | }; 21 | 22 | $scope.validateFile = function ($file) { 23 | $scope.modelState = undefined; 24 | $scope.formUpload.$serverErrors = undefined; 25 | var allowedExtensions = ['jpeg', 'jpg', 'bmp', 'png']; 26 | var isValidType = allowedExtensions.indexOf($file.getExtension()) >= 0; 27 | if (!isValidType) $scope.modelState = { file: ['type'] }; 28 | return isValidType; 29 | }; 30 | 31 | $scope.getSecurityHeaders = function () { 32 | return miscService.getSecurityHeaders(); 33 | }; 34 | } 35 | ]); 36 | -------------------------------------------------------------------------------- /Views/Upload.cshtml: -------------------------------------------------------------------------------- 1 |
2 |
9 | 10 |
17 | Drag and drop your image here or click to upload. 18 | 19 |
20 | 21 |
22 | 23 | {{fileProgress}}% 24 | 25 | 26 | The file is too big 27 | This file type is not supported 28 | Maximum amount of pictures reached 29 | The file appears to be damaged 30 | 31 |
32 |
33 |
34 | --------------------------------------------------------------------------------