使用ASP.NET Core + VueJS上传文件 [英] File upload with ASP.NET Core + VueJS

查看:239
本文介绍了使用ASP.NET Core + VueJS上传文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有ASP.NET core,VueJS应用.
任务是上传带有表单数据的文件
问题:表单数据为空

I have ASP.NET core , VueJS app.
The task is to Upload file with form data
Problem: Form data is null

这是我拥有的HTML和JS类.它使用Jquery Ajax调用来上传模型数据和文件.我无法将第3个库用作Axios(至少我不知道如何使用),但只能使用纯Jquery.

Here is the HTML and JS class I have. Its using Jquery Ajax call to upload model data + file. I am unable to use 3rd libraries as Axios (at least I dont know how) , but pure Jquery.

有人建议它如何工作吗?

Does anybody have suggestion how this can work ?

HTML

<form method = "post" enctype = "multipart/form-data" role = "form" v - on: submit.prevent >
  <div id = "formEditInner" >
     ...
      <div class = "form-group" >
          <label class = "control-label" for  = "photo" > Photo </label >
          <span class = "required" aria - required = "true" >  *  </span >
          <input name = "photo" type = "file" class = "form-control" v - on: change = "addPhoto" placeholder = "Upload photo" >
       </div>
     ...
   </div>
</form >

JS

class ApiClient {

    constructor(url, xhrFields) {
        this._url = url;
        this._xhrFields = xhrFields || { withCredentials: false };
    }


    //THIS METHOD IS IMPORTANT
    _upload(method, url, data, isJson) {
        url = this._url + '/' + url.replace('.', '/');
        if (data && typeof data !== 'object') {
          url += '/' + data;
          data = null;
        }
        let request = { url: url, data: data, type: method, xhrFields: this._xhrFields, crossDomain: true };

        //request.contentType = "multipart/form-data";
        request.contentType = false;  
        request.processData = false;

        return new Promise((res, rej) => {
          request.success = res;
          request.error = rej;
          $.ajax(request);
        });
     }

     uploadAsync(url, data) {
         return this._upload('POST', url, data, false);
     }
 }

服务器代码很好,除了我收到的参数值为NULL

Sever code is fine, except the parameter values I receive are NULL

[AllowAnonymous]
[HttpPost("upload")]
public async Task<bool> Upload(  IList<IFormFile> photo, string zipCode )
{

     return  (photo != null);
}

推荐答案

您可以创建 FormData 并动态附加字段.例如

You can create a FormData and append the fields dynamically. For example,

addPhoto(e){
    var formData = new FormData();
    // field: photo
    for(var i=0; i< e.target.files.length; i++){
        formData.append("photo",e.target.files[i]);
    }
    // field: zipCode
    formData.append("zipCode", '123456');

    // now you can invoke the ApiClient as below : e.g.
    // ... var api = new ApiClient("https://localhost:5001");
    return api.uploadAsync("upload", formData)
        .then(
            r => console.log(r)   // success
        );
},

演示:

这篇关于使用ASP.NET Core + VueJS上传文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆