jsonGPPD
jsonGPPD

Reputation: 1037

Multiple File Upload using Axios & Vue.JS in ASP.NET Core

I'm trying to upload a multiple files/images using vue.js and axios. My backend is ASP.NET Core. But the problem is, whenever I put breakpoint in my request method, I always get a Count = 0 in my controller.

Here are my simple HTML and my codes:

HTML

<div id="app">
    <form enctype="multipart/form-data">
        <input type="file" name="file" multiple="" v-on:change="fileChange($event.target.files)"/>
        <button type="button" @@click="upload()">Upload</button>
    </form>
</div>

My JS

import axios from "axios"

var app= new Vue({
el: "#app",
data: {
    files: new FormData()
},
methods:{
    fileChange(fileList) {
        this.files.append("file", fileList[0], fileList[0].name);
    },
    upload() {
        const files = this.files;
        axios.post(`/MyController/Upload`, files,
            {
                headers: {
                    'Content-Type': 'multipart/form-data'
                }
            }).then(response => {
                alert(response.data);
            }).catch(error => {
                console.log(error);
            });
    },
}

My Controller

public IActionResult Upload(IList<IFormFile> files)
{
    return Json("Hey");
}

Any help please?

Upvotes: 11

Views: 13214

Answers (2)

mark333...333...333
mark333...333...333

Reputation: 1360

This github repo might be helpful for you ASP.NET Core FileUpload with Vue.JS & Axios

Basically, he used the IFormCollection files instead of IList<IFormFile> files

Upvotes: 16

bcnzer
bcnzer

Reputation: 26

I had the same problem. The fix for me was instead to look at the request. You'll see there's a Form property and in there is your file(s). Here's a code snippet that worked for me.

And to give credit where credit is due: I found the answer on this blog post. It's about Angular and the code snippet is from there.

[HttpPost]
public IActionResult UploadLogo()
{
    try
    {
        var file = Request.Form.Files[0];
        string folderName = "Upload";
        string webRootPath = _hostingEnvironment.WebRootPath;
        string newPath = Path.Combine(webRootPath, folderName);
        if (!Directory.Exists(newPath))
        {
            Directory.CreateDirectory(newPath);
        }
        if (file.Length > 0)
        {
            string fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
            string fullPath = Path.Combine(newPath, fileName);
            using (var stream = new FileStream(fullPath, FileMode.Create))
            {
                file.CopyTo(stream);
            }
        }
        return Json("Upload Successful");
    }
    catch (System.Exception ex)
    {
        return Json("Upload Failed: " + ex.Message);
    }
}

Upvotes: 0

Related Questions