使用Axios将上传的图像结果发布到空文件集合中

时间:2018-05-15 13:47:02

标签: .net asp.net-mvc reactjs axios

   const fd = new FormData();
    fd.append('image', this.state.selectedFile, this.state.selectedFile.name);
    const postData = {
        method: 'POST',
        credentials: 'include',
        body: fd
    }

    //this correctly shows the image object and name:
    console.log('selected image file name: ', this.state.selectedFile.name);
    console.log('select image: ', this.state.selectedFile);

    axios({
        method: 'post',
        url: `/api/gameStats/profileImage/${this.props.profileId}/files/upload`,
        postData
    })
    .then(function (response) {
        console.log('then: ', response);
    })
    .catch(function (response) {
        console.log('catch: ', response);
    });


   [HttpPost("upload")]
    public virtual async Task<IActionResult> PostMulti(Int64 parentId, ICollection<IFormFile> fileData)
    {
        'fileData is always empty... :(

        TParent parent;

        using (var tran = Session.BeginTransaction()) {
            parent = Repository.GetParent(parentId);
            if (!Security.CanCreate(CurrentUser, parent, null))
                return StatusCode(HttpStatusCode.Forbidden);
            tran.Rollback();
        }

        foreach (var file in fileData) {
            await SaveFile(file, parent);
        }

        return Created("", Map(Repository.Get(parentId)));
    }

1 个答案:

答案 0 :(得分:1)

您应该在axios请求对象中传递必需的data字段 概述envers

  

// data是要作为请求正文发送的数据     //仅适用于请求方法'PUT','POST'和'PATCH'     //如果未设置transformRequest,则必须是以下类型之一:     // - 字符串,普通对象,ArrayBuffer,ArrayBufferView,URLSearchParams     // - 仅限浏览器:FormData,File,Blob     // - 仅限节点:流,缓冲区     数据:{       firstName:'弗雷德'     },

axios({
        method: 'post',
        url: `/api/gameStats/profileImage/${this.props.profileId}/files/upload`,
        data: postData
    })

P上。 S.当您追加FormData时,您不需要传递文件名,因为如果它是File类型here,则会自动从中导出文件名。

  

当Blob或File作为第二个参数传递时,向服务器报告的文件名(USVString)。 Blob对象的默认文件名是“blob”。 File对象的默认文件名是文件的文件名。

fd.append('image', this.state.selectedFile);