Angular上传文件至ASP.NET 6后端遇System.FormatException求助
Angular上传文件到ASP.NET 6后端出现FormatException问题解决
问题概述
Angular应用向ASP.NET 6后端API上传文件时,抛出System.FormatException: Input string was not in a correct format错误,后端代码未触发调试断点,但通过Swagger测试该接口可正常工作。
客户端代码
onFileSelected(event: any) { this.selectedFile = event.target.files[0]; const formData = new FormData(); formData.append('file', this.selectedFile, this.selectedFile.name); debugger; const file: File = event.target.files[0]; // const formData = new FormData(); // formData.append('file', file); this.http.post(this.BaseUrl + '/api/FileUpload/upload', formData).subscribe(response => { console.log('File uploaded successfully'); }); }
后端代码
[HttpPost("upload")] public async Task<IActionResult> Upload(IFormFile file) { // Retrieve the connection string from configuration var connectionString = _storageConnectionString; // Create a BlobServiceClient object var blobServiceClient = new BlobServiceClient(connectionString); // Get a reference to the container where you want to upload the file var containerName = "mycontainer"; var containerClient = blobServiceClient.GetBlobContainerClient(containerName); // Create a unique name for the blob var fileName = Guid.NewGuid().ToString() + Path.GetExtension(file.FileName); // Upload the file to Azure Storage var blobClient = containerClient.GetBlobClient(fileName); await blobClient.UploadAsync(file.OpenReadStream(), true); // Return a response to the client return Ok(); }
解决步骤
1. 移除手动设置的Content-Type请求头
Angular的HttpClient在发送FormData时,会自动生成正确的multipart/form-data请求头及边界符,手动设置该头会导致格式解析错误。检查全局HTTP拦截器或当前请求是否手动添加了Content-Type,如有则移除。
优化后的客户端代码:
onFileSelected(event: any) { const file = event.target.files[0]; if (!file) return; const formData = new FormData(); formData.append('file', file, file.name); this.http.post(`${this.BaseUrl}/api/FileUpload/upload`, formData).subscribe({ next: () => console.log('File uploaded successfully'), error: (err) => { console.error('上传失败:', err); console.error('错误详情:', err.error); } }); }
2. 确认后端表单解析配置
ASP.NET 6默认启用表单数据解析,可检查Program.cs确保MVC服务已正确注册:
var builder = WebApplication.CreateBuilder(args); // 添加Controllers服务(默认包含表单解析支持) builder.Services.AddControllers(); var app = builder.Build(); app.UseHttpsRedirection(); app.UseAuthorization(); app.MapControllers(); app.Run();
3. 配置跨域(若前后端域名不同)
如果Angular应用和后端API不在同一域名下,需在后端配置CORS:
builder.Services.AddCors(options => { options.AddPolicy("AllowAngular", policy => { policy.WithOrigins("http://localhost:4200") // 替换为你的Angular应用地址 .AllowAnyHeader() .AllowAnyMethod(); }); }); // 在UseAuthorization之前添加UseCors app.UseCors("AllowAngular"); app.UseAuthorization(); app.MapControllers();
4. 捕获前端完整错误信息
通过错误回调获取详细错误内容,进一步定位问题:
this.http.post(`${this.BaseUrl}/api/FileUpload/upload`, formData).subscribe({ next: () => console.log('文件上传成功'), error: (error) => { console.log('错误状态码:', error.status); console.log('错误消息:', error.message); console.log('错误详情:', error.error); } });
内容的提问来源于stack exchange,提问作者Sanidh
相关产品推荐
相关产品推荐

