我有一个MVC应用程序,我在Windows Server 2016 AWS EC2实例上托管。此应用程序是一个管理工具。此应用程序使用托管为AWS Lambda无服务器应用程序(https://docs.aws.amazon.com/toolkit-for-visual-studio/latest/user-guide/lambda-build-test-severless-app.html)的Web API应用程序。
我的MVC应用程序的一个区域允许用户使用表单文件输入上传图像。然后将其发回MVC控制器并发送到API实用程序,该实用程序将文件发送到API。然后API调整大小(使用Magick.NET)并将图像保存到S3存储桶,并将结果URL保存到MySQL数据库。
这在我的机器上本地运行时完美无缺。问题是当我尝试在实时网站上传图像时。结果是当图像数据加载到MagickImage时,我收到以下错误:
ImageMagick.MagickCorruptImageErrorException:不是JPEG文件:以0xef 0xbf开头`'@ error / jpeg.c / JPEGErrorHandler / 332 \ n
我添加了一些代码来记录MVC应用程序(文件发布到API之前)和API文件收到后的数据的前20个字节(这是一个字节数组)。我发现我收到的价值完全不同,如下所示:
- MVC:FF-D8-FF-E0-00-10-4A-46-49-46-00-01-01-01-01-2C-01-2C-00-00
- API:EF-BF-BD-EF-BF-BD-EF-BF-BD-EC-BF-BD-00-10-4A-46-49-46-00-01
然后我在本地运行时执行以下操作,并看到输出的值相同:
- MVC:FF-D8-FF-E0-00-10-4A-46-49-46-00-01-01-01-01-2C-01-2C-00-00
- API:FF-D8-FF-E0-00-10-CHA-46-49-46-00-01-01-01-01-2Ts-01-2Ts-00-00
我需要设置/更改哪种环境设置可能导致这种奇怪的行为?
以下是按发生顺序相关的不同代码部分。
MVC控制器:
public async Task<IActionResult> AddImage(ImageFormViewModel viewModel)
{
if (!ModelState.IsValid)
{
return RedirectToAction("Details", new { id = viewModel.TourId, errors = string.Join(",", ViewData.ModelState.Values.SelectMany(x => x.Errors.Select(y => y.ErrorMessage))) });
}
var apiResponse = await this.api.PostFile<ApiResponse>($"tours/{viewModel.TourId}/images", viewModel.Image);
if (apiResponse.Success)
{
return RedirectToAction("Details", new { id = viewModel.TourId, message = "Image added successfully!" });
}
{
return RedirectToAction("Details", new { id = viewModel.TourId, errors = string.Join(",", apiResponse.Errors) });
}
}
API实用程序(在MVC应用程序中):
public async Task<TResponse> PostFile<TResponse>(string uri, IFormFile file) where TResponse : ApiResponse
{
var response = default(TResponse);
if (file != null && file.Length > 0)
{
var url = (!string.IsNullOrWhiteSpace(uri) ? new Uri(new Uri(this.baseUrl), uri) : new Uri(this.baseUrl)).ToString();
using (var http = new HttpClient())
{
byte[] data;
using (var stream = new MemoryStream())
{
await file.CopyToAsync(stream);
data = stream.ToArray();
}
this.logger.Information("First bytes (MVC app): " + BitConverter.ToString(data.Take(20).ToArray()));
var content = new MultipartFormDataContent();
content.Add(new ByteArrayContent(data), "file", file.FileName);
var httpResponse = await http.PostAsync(url, content);
response = JsonConvert.DeserializeObject<TResponse>(await httpResponse.Content.ReadAsStringAsync());
}
}
return response;
}
API控制器:
[HttpPost]
public async Task<IActionResult> Post([FromRoute]string tourId)
{
var response = new ApiResponse();
if (Request.HasFormContentType)
{
var form = Request.Form;
foreach (var formFile in form.Files)
{
using (var stream = new MemoryStream())
{
await formFile.CopyToAsync(stream);
var result = await this.tourManagementService.AddImage(HttpUtility.UrlDecode(tourId), Path.GetFileNameWithoutExtension(formFile.FileName), stream.ToArray());
if (!result.Success)
{
...
}
}
}
}
return Ok(response);
}
保存图像的服务方法等:
public async Task<AddImageResult> AddImage(string tourId, string imageName, byte[] imageData)
{
this.logger.Information("First bytes (API): " + BitConverter.ToString(imageData.Take(20).ToArray()));
...
}
使用Magick.NET的代码并抛出异常:
private byte[] resizeImage(byte[] imageData, int width, int height)
{
using (var image = new MagickImage(imageData, new MagickReadSettings { Format = MagickFormat.Jpeg }))
{
...
}
}
问题是我的AWS API Gateway不接受二进制数据。默认情况下,API Gateway将消息正文视为JSON,如此处所述 - https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-payload-encodings.html
默认情况下,API Gateway将消息正文视为文本有效内容,并应用任何预配置的映射模板来转换JSON字符串。
我相信这是腐败的根源。为了解决这个问题,我不得不在API网关中添加“image / jpeg”作为可接受的二进制媒体类型,如下所示:
然后我调整了我的代码以处理二进制数据(并废弃了表单内容的东西):
MVC方面:
public async Task<TResponse> PostFile<TResponse>(string uri, IFormFile file) where TResponse : ApiResponse
{
var response = default(TResponse);
if (file != null && file.Length > 0)
{
var url = (!string.IsNullOrWhiteSpace(uri) ? new Uri(new Uri(this.baseUrl), uri) : new Uri(this.baseUrl)).ToString();
using (var http = new HttpClient())
{
var content = new StreamContent(file.OpenReadStream());
content.Headers.ContentType = new MediaTypeHeaderValue(file.ContentType);
var httpResponse = await http.PostAsync(url, content);
response = JsonConvert.DeserializeObject<TResponse>(await httpResponse.Content.ReadAsStringAsync());
}
}
return response;
}
API方面:
[HttpPost]
public async Task<IActionResult> Post([FromRoute]string tourId)
{
var response = new ApiResponse();
if (Request.ContentType.Equals("image/jpeg"))
{
using (var stream = new MemoryStream())
{
await Request.Body.CopyToAsync(stream);
...
}
}
else
{
...
}
return Ok(response);
}