1
  1. I render image uploader in html using this function. which correctly display image in page. How should I post this FileReader to controller?
       showCoverImage(e) {
            
            var file = e.target.files[0];
    
            var imageType = /image.*/;
    
            if (!file.type.match(imageType)) {
                return;
            }
    
            var img = document.getElementById("thumbnail");
            img.file = file;
    
            const fileName = document.querySelector('#cover-image .file-name');
            fileName.textContent = file.name;
    
            var reader = new FileReader();
            reader.onload = (function (aImg) {
                return function (e) {
                    aImg.src = e.target.result;
                };
            })(img);
            reader.readAsDataURL(file);
        }
  1. I have controller method for upload using IFromFIle. It receives IFromFIle as parameter.
[HttpPost("/upload/coverImage")]
        public async Task<IActionResult> uploadEditorImage(IFormFile upload)
        {
            var fileName = upload.FileName;
            var path = Path.Combine(_mainDirectory, "images");
            var pathPath = Path.Combine(path, fileName);
    
            int isUpload = 1;
            string errorMsg = string.Empty;
            try
            {
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
    
                var stream = new FileStream(pathPath, FileMode.Create);
    
                await upload.CopyToAsync(stream);
    
                await stream.FlushAsync();
     
    
            return new JsonResult(new {uploaded:1});
        }
  1. Upload call using axios. It posts to controller IFromFile as null.
     onCoverImageUpload() {
            this.loading = true;

            const formData = new FormData();
            formData.append("file", this.selectedCoverImage);

            let config = {
                headers: {
                    "Content-Type": "multipart/form-data"
                }
            };

            axios.post('/upload/coverImage', formData, config)
                .then(res => {
                    console.log(res);
                });
        }
ahnirab
  • 168
  • 1
  • 11
  • Is this link answer your question? https://stackoverflow.com/questions/43013858/how-to-post-a-file-from-a-form-with-axios – Raju Melveetilpurayil Oct 23 '20 at 18:43
  • const formData = new FormData(); formData.append('image',e.target.files[0]); axios.post('/upload', formData, { headers: { 'Content-Type': 'multipart/form-data' } }) .then(res => { console.log(res); }) }, If I post this way, still receives null in IFormFile upload variable of controller – ahnirab Oct 23 '20 at 19:36
  • Are you sure that you posting to ```uploadEditorImage``` action, I cant see that ```axios.post``` – Raju Melveetilpurayil Oct 23 '20 at 19:54
  • Ohh, It was typo in previous comment. I am posting to axios.post('/upload/uploadEditorImage'.......... I debug and received null to upload variable. – ahnirab Oct 24 '20 at 04:25
  • If you can update the question bit more clearly like adding some more code, will help us to understand the issue bit more detail – Raju Melveetilpurayil Oct 24 '20 at 09:33

2 Answers2

0

First, ensure you could get the file by this.selectedCoverImage.

Second, the name is inconsistent. Change the name file in the formData to upload

formData.append("upload", this.selectedCoverImage);
mj1313
  • 7,930
  • 2
  • 12
  • 32
  • I checked, `formData.append("file", this.selectedCoverImage);` and `this.selectedCoverImage` is fine while post. Same result, Controller received null. – ahnirab Oct 26 '20 at 10:59
0

Finally I changed my controller implementation. Now working.

[HttpPost("/upload/coverImage")] 
public async Task<IActionResult> uploadEditorImage()
{ 
      var upload = Request.Form.Files[0];
      var fileName = upload.FileName; 
      var path = Path.Combine(_mainDirectory, "images"); 
      var pathPath = Path.Combine(path, fileName); 
      string errorMsg = string.Empty; 

      try { 
            if (!Directory.Exists(path)) {
                  Directory.CreateDirectory(path);
           }

        var stream = new FileStream(pathPath, FileMode.Create); 
         await upload.CopyToAsync(stream); 
          await stream.FlushAsync(); 
        return new JsonResult(new {uploaded:1}); 
} 
ahnirab
  • 168
  • 1
  • 11