问题描述
限时送ChatGPT账号..我有一个带有 angular 6
的 fileUploader
组件,在服务器端我使用 Asp.Net Core 2.0
.由于我的文件很大,我使用 FormData
.
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:
组件:
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);
});
}
}
服务:
@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 服务器:
public async Task<IActionResult> UploadFile(AttDTO model)
{
//...
}
DTO 类:
public class AttDTO
{
public IFormFile file { get; set; }
public string att { get; set; }
}
我需要将带有数据的文件数组发送到带有FormData
的服务器.在 server
中是这样的:
I need to send array of file with data to server with FormData
.
like this in server
:
服务器:
public async Task<IActionResult> UploadFile(List<AttDTO> obj)
{
//...
}
服务
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);
}
我该怎么做?
客户端(组件、服务)有什么变化?
What's change in client side (component , service)?
有人可以帮我吗?
推荐答案
一天后,我找到了解决方案.
after one day, I found the solution.
按照这个:
服务:
将 att
对象移动到 after 循环并将所有 lst 转换为 stringify.像这样:
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);
}
在服务器端
我从 Request.Form
而不是 parameter
接收数据.像这样:
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;
}
// ...
}
希望有用.
这篇关于如何使用 FormData 将文件和数据数组发送到 API 服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论