简体   繁体   English

将包含数据和文件的javascript对象发送到asp.net核心

[英]Send javascript object with data and file to asp.net core

I need send data with file in a javascript object to asp.net core but when it arrives at the asp.net core method, arrives with null values ( List<Upload> listUpload ) 我需要将数据与javascript对象中的文件一起发送到asp.net core但是当它到达asp.net核心方法时,到达时带有空值( List<Upload> listUpload

I did a test removing the File property from the javascript object and it does not appear anymore null, the problem is with the File property that it can not map with the model property called File of type IFormFile. 我做了一个测试从javascript对象中删除File属性并且它不再出现null,问题在于File属性它无法映射到名为File类型IFormFile的模型属性。

javascript code: javascript代码:

jQuery('#tblDocuments > tbody > tr').each(function () {
   checkBox = jQuery(this).find('td').eq(0).children();

   inputFile = jQuery(this).find('td').eq(2).children()[0].files[0]; 

    let Upload = {
        File: inputFile,
        CodigoVendaArquivo: res,
        CodigoClienteArquivo: cliente,
        Checkbox: checkBox[0].id
    };
    listUpload.push(Upload);
});

I'm trying to send with fetch : 我正试图用fetch发送:

fetch('../../upload', {
    method: 'POST',
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
    },
    body: JSON.stringify(listUpload)
}).then(res => res.json())
.then(res => {

    if (res == 1) {
     // success
    }

});

Here's my asp.net core method: 这是我的asp.net core方法:

[Route("upload")]
[HttpPost]
public JsonResult Upload([FromBody] List<Upload> listUpload)
{
    // something
}

Here's my Model: 这是我的模型:

public class Upload
{
    public IFormFile File { get; set; }
    public string CodigoVendaArquivo { get; set; }
    public string CodigoClienteArquivo { get; set; }
    public string Checkbox { get; set; }
}

Avoid embedding an IFormFile within the Upload class. 避免在Upload类中嵌入IFormFile When uploading something like IList<Upload> where its list item has a property of IFormFile , you might encounter an bug that results in a crazy memory leak (It ate me about 6.7G memory until I address it). 当上传像IList<Upload>这样的列表项具有IFormFile属性的IFormFile ,你可能会遇到一个导致疯狂内存泄漏的错误 (在我解决它之前我吃了大约6.7G的内存)。 For more information, see 有关更多信息,请参阅

The easiest way to walk around it, as WahidBitar comments on GitHub , is to create a wrapper to receive the payload. WahidBitar在GitHub上评论的那样,最简单的方法就是创建一个包装来接收有效载荷。


As for your question itself, you should avoid embedding an IFormFile within the Upload class. 至于你的问题本身,你应该避免在Upload类中嵌入IFormFile

Here's a working sample : 这是一个工作样本:

public class UploadPayload{
    public IList<Upload> Uploads{get;set;}

    public class IFormFileWrapper {
        public IFormFile File { get; set; }
    }
    public class Upload
    {
        // See https://github.com/aspnet/Mvc/issues/8782
        
 

 
 
  
  
 
  public IFormFile File { get; set; }
 

 
 
        public IFormFileWrapper CodigoFile { get; set; }
        public string CodigoVendaArquivo { get; set; }
        public string CodigoClienteArquivo { get; set; }
        public string Checkbox { get; set; }
    }
}

And also change your action method as below: 并且还更改您的操作方法如下:

 
 
  
  
 
  public JsonResult Upload([FromBody] List listUpload)
 

 
 
public IActionResult Upload(UploadPayload listUpload)
{ 
    ... 
}

Client Side : 客户端 :

To construct a formData , create a getFormData() function : 要构造formData ,请创建一个getFormData()函数:

    function getFormData(listUpload){
        var formData = new FormData();
        function getFieldName(index,name){
            return "Uploads[" + index + "]." + name ;
        };
        function getFileName(index,name){
            return "Uploads[" + index + "].CodigoFile." + name ;
        };

        for(var i =0 ;i <listUpload.length; i++){
            var upload = listUpload[i];
            formData.append(getFieldName(i, 'CodigoVendaArquivo'), upload.CodigoVendaArquivo);
            formData.append(getFieldName(i, 'CodigoClienteArquivo'), upload.CodigoClienteArquivo);
            formData.append(getFieldName(i, 'Checkbox'),upload.Checkbox)
            formData.append(getFileName(i, 'File'), upload.File);
        }
        return formData;
    }

Now we could send the formData in the following way: 现在我们可以通过以下方式发送formData:

jQuery('#tblDocuments > tbody > tr').each(function () {
        ...
        listUpload.push(Upload);
    }

    var formData = getFormData(listUpload);
    fetch('../../upload', {
        method: 'POST',
        headers: {
            'Accept': 'application/json',
            
 

 
 
  
  
 
  'Content-Type': 'application/json'
 

 
 
        },
        
 

 
 
  
  
 
  body: JSON.stringify(listUpload),
 

 
 
        body:formData,
    })
    .then(res => res.json())
    .then(res => {
        if (res == 1) {
            // success
        }
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将Javascript文件对象+数据发送到MVC 6控制器-ASP.NET 5 - How to send Javascript File Object+ Data to MVC 6 Controller - ASP.NET 5 How to POST javascript object, javascript object list and file list to asp.net core controller - How to POST javascript object, javascript object list and file list to asp.net core controller ASP.NET Core 2.1 MVC 使用 XMLHttpRequest 将数据从 JavaScript 发送到 Action 方法 - ASP.NET Core 2.1 MVC send data from JavaScript to Action method using XMLHttpRequest 将表单数据从 React 发送到 ASP.NET Core API - Send form data from React to ASP.NET Core API 使用 AJAX () 将 Javascript 中的数组对象数据发送到 ASP.NET Core 控制器 - Sending Array Object Data in Javascript to ASP.NET Core Controller using AJAX () 如何在asp.net Core中将模型对象传递给javascript函数 - How to pass model object to javascript function in asp.net Core 使用 vanilla javascript ajax [ASP.NET Core] 在同一个 POST 请求中上传文件和 Json 数据 - Upload file and Json data in the same POST request using vanilla javascript ajax [ASP.NET Core] 将具有未知属性的JavaScript对象发送到asp.net MVC控制器 - send JavaScript object with unknown properties to asp.net MVC controller 如何在javascript中将json对象发送到asp.net? - how to send json object to asp.net in javascript? 将复杂的JavaScript对象发送到ASP.Net MVC操作 - Send complex JavaScript object to ASP.Net MVC Action
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM