How to send array of files and data to API server with FormData

a 夏天 提交于 2020-03-05 04:13:34

问题


I hava a fileUploader component with angular 6 and in the server side I use the Asp.Net Core 2.0. Since the my files has larg size, I use the FormData.

I can send a file with data to server very well. with this code:

component:

export class AttComponent implements OnInit
{
    constructor(private attService: AttService) { }
    uploadFile()
    {
        var entity = {};
            entity.ID = 123;
            entity.ATT_ID = 456;
            entity.REFERENCE_TYPE = "referenceType";
            entity.REFRENCE_ID = "referenceID";

        this.attService.UploadFile(fileUploader.files[0], entity).subscribe((data: IServiceResult) =>
                {
                    console.log("fileUploader result => ", data);
                });
    }
}

service:

@Injectable()
export class AttService
{
    UploadFile(file, entity: any): Observable<any> 
    {
            var formData = new FormData();
            formData.append('file', file);
            formData.append('att', JSON.stringify(entity));
            return this.http.Post("/UploadFile", formData);
    }
}

Api Server:

public async Task<IActionResult> UploadFile(AttDTO model)
{
    //...
}

DTO Class:

public class AttDTO
    {
        public IFormFile file { get; set; }
        public string att { get; set; }
    }

I need to send array of file with data to server with FormData. like this in server:

server:

public async Task<IActionResult> UploadFile(List<AttDTO> obj)
{
    //...
}

service

uploadFile(lst: Array<any>): Observable<any>
    {
        var formData = new FormData();
        lst.forEach(item =>
        {
            formData.append('file', item.fILE);
            formData.append('att', JSON.stringify(item.att));
        });
        return this.http.Post("/UploadFile", formData);
    }

How do i do?

What's change in client side (component , service)?

Can anyone help me?


回答1:


Try below code.

Component:

                           Send all files
                            \/\/\/\/\/\/
this.attService.UploadFile(fileUploader.files, entity).subscribe((data:IServiceResult) => {
    console.log("fileUploader result => ", data);
});

UploadFile() method in Service:

UploadFile(files, entity: any): Observable<any> {
 let data: any[] = []
  this.foods.forEach(file => {
    var formData = new FormData();
    formData.append('file', item.fILE);
    formData.append('att', JSON.stringify(item.att));
    data.push(formData);
  });

 return this.http.Post("/UploadFile", data);
}

API Side change:

public class AttDTO
{
  public IFormFile file { get; set; }
  public string att { get; set; }
}

and method:

public async Task<IActionResult> UploadFile(IList<AttDTO> obj)
{
    //...
}



回答2:


after one day, I found the solution.

follow this:

service:

move att object to after loop and cast all of the lst to stringify. like this:

uploadFile(lst: Array<any>): Observable<any>
    {
        var formData = new FormData();
        lst.forEach(item =>
        {
            formData.append('file', item.fILE);
        });
        formData.append('att', JSON.stringify(lst));
        return this.http.Post("/UploadFile", formData);
    }

In server side

I recieve data from Request.Form instead parameter. like this:

[HttpPost]
        public async Task<IActionResult> UploadFile()
        {
            var att = Request.Form.ToDictionary(x => x.Key, x => x.Value.ToString())["att"];
            var json = (JArray)Newtonsoft.Json.JsonConvert.DeserializeObject(att);

            List<AttDTO> lst = new List<AttDTO>();

            int i = 0;
            foreach (var item in json.Children())
            {
                lst.Add(new AttDTO() { att = item.ToString(), file = Request.Form.Files[i] });
                ++i;
            }
            // ...
        }

I hope is useful.



来源:https://stackoverflow.com/questions/57024928/how-to-send-array-of-files-and-data-to-api-server-with-formdata

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!