【问题标题】:Multiple File Upload using Axios & Vue.JS in ASP.NET Core在 ASP.NET Core 中使用 Axios 和 Vue.JS 进行多文件上传
【发布时间】:2018-08-27 13:56:32
【问题描述】:

我正在尝试使用 vue.js 和 axios 上传多个文件/图像。我的后端是 ASP.NET Core。但问题是,每当我在请求方法中放置断点时,我的控制器中总是会得到一个 Count = 0 。

这是我的简单 HTML 和我的代码:

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>

我的 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);
            });
    },
}

我的控制器

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

有什么帮助吗?

【问题讨论】:

  • 这是什么@@click
  • 在 ASP.NET Core Razor 中,它相当于@。只是 Razor 的约定,所以我们使用 @@ 而不是 @。但它的工作原理
  • 尝试检查浏览器网络是否正确发送了请求并带有相应的文件数据。
  • 我也面临同样的问题。除了下面答案中的链接之外还有什么运气吗?

标签: file-upload vue.js asp.net-core-mvc axios


【解决方案1】:

我遇到了同样的问题。对我来说,解决方法是查看请求。您会看到有一个 Form 属性,其中有您的文件。这是一个对我有用的代码 sn-p。

并在应得的地方给予赞扬:我找到了答案on this blog post。这是关于 Angular 的,代码 sn-p 来自那里。

[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);
    }
}

【讨论】:

    【解决方案2】:

    这个 github repo 可能对你有帮助 ASP.NET Core FileUpload with Vue.JS & Axios

    基本上,他使用IFormCollection files而不是IList&lt;IFormFile&gt; files

    【讨论】:

    • 经过多次头部撞击后,参数中的微小差异完美运行,谢谢,希望我在 4 小时前找到这个
    猜你喜欢
    • 1970-01-01
    • 2010-12-31
    • 2023-03-04
    • 1970-01-01
    • 2010-10-08
    • 1970-01-01
    • 2020-04-09
    • 1970-01-01
    • 2018-08-30
    相关资源
    最近更新 更多