How to insert files to angular ViewModel with DropzoneJS

I`m trying to get file content and insert it into specific FileViewModel. The reason is that I need to send all files with MainViewModel that contain a list of FileViewModel from a client (angular) to server (.Net WebApi)

Any Idea how to implement that?

Client ViewModels:

exprot class MainRequestViewModel{
  public FirstName: string;
  public LastName: string;
  public Comments: string;
  public FilesToUpload: Array<FileItemRequestViewModel>;
}

export class FileItemRequestViewModel{
  public FileContent: ArrayBuffer = null;
  public FileMimeType: string;
  public FileName: string;
  public NumberOfPagesInFile: number;
  public ItemPriority: number;
}

1 answer

  • answered 2018-04-17 06:08 Ben Croughs

    I have 2 suggestions:

    1) smaller files, like images, attachments. You can sent them base64encoded over the wire, mind the limits of the payload you send to your webapi (defined in web.config)

    in your entity define a property

    fileAsBase64: string
    

    you can then convert a File from the dropzone component to a base64 string

    getBase64(file) {
        return new Promise((resolve, reject) => {
          const reader = new FileReader();
          reader.readAsDataURL(file);
          reader.onload = () => resolve(reader.result);
          reader.onerror = (error) => reject(error);
    });
    

    on the C# end, you can also define the file as a string, and use this to convert the string back to a byte array

     public class UploadedFileDto
        {
            public string Name { get; set; }
            public string FileAsBase64 { get; set; }
    
            [JsonIgnore]
            public string MimeType => Regex.Match(FileAsBase64, @"data:(?<type>.+?);base64,(?<data>.+)").Groups["type"].Value;
    
            [JsonIgnore]
            public byte[] Bytes =>
                Convert.FromBase64String(Regex.Match(FileAsBase64, @"data:(?<type>.+?);base64,(?<data>.+)").Groups["data"].Value);
    
        }
    

    2: when dealing with larger files

    sent the files in a separate call to the server and save them temporary. In this case you will also need a function to clean these temp files, here is a controller snippet, with size check and only allow pdf

    public async Task<HttpResponseMessage> Upload()
        {
    
    
            Dictionary<string, object> dict = new Dictionary<string, object>();
            try
            {
    
                var httpRequest = HttpContext.Current.Request;
    
                foreach (string file in httpRequest.Files)
                {
    
                    HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created);
    
                    var postedFile = httpRequest.Files[file];
    
    
                    if (postedFile != null && postedFile.ContentLength > 0)
                    {
                        int MaxContentLength = 1024 * 1024 * 50; //Size = 50 MB  
    
                        IList<string> AllowedFileExtensions = new List<string> { ".pdf" };
                        var ext = postedFile.FileName.Substring(postedFile.FileName.LastIndexOf('.'));
                        var extension = ext.ToLower();
                        if (!AllowedFileExtensions.Contains(extension))
                        {
    
                            var message = string.Format("Please upload file of type .pdf");
    
                            dict.Add("error", message);
                            return await Task.FromResult(Request.CreateResponse(HttpStatusCode.BadRequest, dict));
                        }
                        else if (postedFile.ContentLength > MaxContentLength)
                        {
    
                            var message = string.Format("Please upload a file upto 50 mb.");
    
                            dict.Add("error", message);
                            return await Task.FromResult(Request.CreateResponse(HttpStatusCode.BadRequest, dict));
                        }
                        else
                        {
                            _fileService.SaveUploadedFile(postedFile);
    
                        }
                    }
    
                    var message1 = string.Format("File uploaded Successfully.");
                    return await Task.FromResult(Request.CreateResponse(HttpStatusCode.OK, message1)); ;
                }
                var res = string.Format("Please upload a pdf.");
                dict.Add("error", res);
                return Request.CreateResponse(HttpStatusCode.BadRequest, dict);
            }
            catch (Exception ex)
            {
                Log.Error(ex);
                var res = string.Format("Errors occured");
                dict.Add("error", res);
                return await Task.FromResult(Request.CreateResponse(HttpStatusCode.InternalServerError, dict));
            }
        }