我正在编写一个Reactjs应用程序,并向ASP.Net Core2.0后端api项目发布一个文件和一个字符串,如下所示。我想将一个文件和一个字符串值发布到后端。但它总是显示出错误。
f.append("File",filesArray[i][0]);
f.append("member_code", this.state.member_code);
axios.post(apiBaseUrl
, f, {
headers: {'Content-Type': 'multipart/form-data'}
})
.then((response) => {
var result = response.data;
if(result[0].status == "1")
{
this.state.filesNames.push(result[0].filename);
if((i +1) == filesArray.length){
window.HideModal();
this.setState({filesPreview: null, filesToBeSent: null});
this.props.onClick(this.state.filesNames);
}
}
});
在我的ASP.Net核心项目中,我尝试了如下所示:
[HttpPost]
[Route("upload")]
public async Task<IActionResult> Upload(FileUploadViewModel[] model)
{
var file = model.File;
var member_code = "test";
if (file.Length > 0)
{
string path = Path.Combine(_env.WebRootPath, "uploadFiles/member_files/" + member_code);
bool exists = System.IO.Directory.Exists(path);
if (!exists)
System.IO.Directory.CreateDirectory(path);
using (var fs = new FileStream(Path.Combine(path, file.FileName), FileMode.Create))
{
await file.CopyToAsync(fs);
}
}
return clsCommonFunctions.ConstructFileUploadResponse(clsConfig.status_success, file.FileName);
}
但是在ASP.Net核心函数中,我不能同时接受作为多部分/表单数据传递的文件和字符串值。
有人建议我如何将文件和字符串值作为FormData在ASP.Net核心项目中接受。
谢谢。
发布于 2017-11-20 11:20:18
这个文章帮了我很多忙。我只是通过使用FromBody属性从请求表单数据中获取特定值来解决我的问题。最后的代码如下:
[HttpPost]
[Route("upload")]
public async Task<IActionResult> Upload([FromForm] FileUploadViewModel model, [FromForm] string member_code)
{
var file = model.File;
if (file.Length > 0)
{
string path = Path.Combine(_env.WebRootPath, "uploadFiles/member_files/" + member_code);
bool exists = System.IO.Directory.Exists(path);
if (!exists)
System.IO.Directory.CreateDirectory(path);
using (var fs = new FileStream(Path.Combine(path, file.FileName), FileMode.Create))
{
await file.CopyToAsync(fs);
}
}
return clsCommonFunctions.ConstructFileUploadResponse(clsConfig.status_success, file.FileName);
}
https://stackoverflow.com/questions/47390576
复制相似问题