我想使用Angular 7和Asp.net core 2.2上传文件
在Angular Web服务中,附加文件并附加属性Name
当通过Angular调用WebSerice时,在Asp.net核心日志中显示此错误。
我已阅读this问题,并在Content-Type中添加了utf-8
,但再次显示错误。
我该如何解决?是Content-Type
的问题吗?
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware:Error: An unhandled exception has occurred while executing the request.
System.Text.DecoderFallbackException: Unable to translate bytes [FF] at index 144 from specified code page to Unicode.
at System.Text.DecoderExceptionFallbackBuffer.Throw(Byte[] bytesUnknown, Int32 index)
at System.Text.DecoderExceptionFallbackBuffer.Fallback(Byte[] bytesUnknown, Int32 index)
at System.Text.DecoderFallbackBuffer.InternalFallback(Byte[] bytes, Byte* pBytes, Char*& chars)
at System.Text.UTF8Encoding.FallbackInvalidByteSequence(Byte*& pSrc, Int32 ch, DecoderFallbackBuffer fallback, Char*& pTarget)
Asp.net核心:
[HttpPost("[action]")]
[AllowAnonymous]
public async Task<ReturnFromSpDto> AddFileInsertAsync(Test1 name)
{ .. }
Test1类:
public class Test1
{
public string Name { get; set; }
}
角度HTML:
<input #file type="file" multiple (change)="upload(file.files)" />
角度:
upload(files) {
if (files.length === 0)
return;
const formData = new FormData();
formData.append(files[0].name, files[0]);
const headers = new HttpHeaders({ "Content-Type": "application/json; charset=utf-8" });
headers.append('Accept', 'application/json');
formData.append('Name', 'ads');
console.log('formData', formData);
const uploadReq = new HttpRequest('POST',
`${this.appConfig.apiEndpoint}/api/doc/AddFileInsertAsync`, formData, {
headers: headers,
reportProgress: true,
});
this.httpClient.request(uploadReq).subscribe(event => {
if (event.type === HttpEventType.UploadProgress)
this.progress = Math.round(100 * event.loaded / event.total);
else if (event.type === HttpEventType.Response)
this.message = event.body.toString();
});
}
答案 0 :(得分:1)
尝试直接删除标题,并使用以下代码发送帖子请求
upload(files) {
if (files.length === 0)
return;
const formData: FormData = new FormData();
formData.append('name', 'ads');
formData.append('file', files[0], files[0].name);
this.httpClient.post( `${this.appConfig.apiEndpoint}/api/doc/AddFileInsertAsync`, formData).subscribe(result => {
console.log(result);
}, error => console.error(error));
}
型号:
public class Test1
{
public string Name { get; set; }
public IFormFile File { get; set; }
}
操作:
[HttpPost("[action]")]
[AllowAnonymous]
public async Task<ReturnFromSpDto> AddFileInsertAsync([FromForm]Test1 test)
{ .. }
答案 1 :(得分:0)
在将文件追加到formData时使用:
formData.append('file', file, file.name);
您使用文件名作为表单字段名称,这可能会导致问题,
2号请勿将Content-Type
设置为application/json
,而将其保留为x-www-form-urlencoded
。