无法从 chrome 扩展将图像上传到 .net core webapi

问题描述 投票:0回答:1

我尝试截取活动选项卡的屏幕截图并将其从 Chrome 扩展上传到 .net core Web api。调用 Web api 后,我不断收到“HTTP 错误:400”。我不确定我做错了什么,如果有人可以提供帮助,我将不胜感激。

更新1:我终于找到了为什么会出现400错误,这是因为fetch-api不会自动为Content-Type添加边界。通过从标头中删除 Content-Type,这解决了问题,现在 fetch-api 可以成功连接到控制器。现在我有另一个问题,模型的 RequestModel.File 为空...

这是service-worker.js中的代码

chrome.action.onClicked.addListener(async function () {
  await TestPost();
});

async function TestPost() {
  const url = "https://localhost:7221/test/upload"; // This link has been tested with a c# app

  const tabCapture = await chrome.tabs.captureVisibleTab(); // This also has been tested and works

  const formData = new FormData();
  formData.append("filename", "my-file-name");
  formData.append("file", tabCapture);

  debugger;

  fetch(url, {
    method: "POST",
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'multipart/form-data'
    },
    body: formData
  })
  .then((response) => {
    if (!response.ok) {
      throw new Error(`HTTP error: ${response.status}`);
    }
    return response.json();
  })
  .then((data) => {
    console.log(data[0].name);
  })  
  .catch(error => console.log("ERROR - TestPost: " + error)); 
};

这是.net core控制器

        [HttpPost("upload")]
        public async Task<IActionResult> Upload([FromForm] RequestModel model)
        {
            try
            {
                var filename = model.FileName;
                var uploadFileFullPath = Path.Combine("my-uploadpath", $"{DateTime.Now.ToString("yyyyMMdd HHmmss")}.jpg");

                using (var fileStream = new FileStream(uploadFileFullPath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None))
                {
                    await model.File.CopyToAsync(fileStream);
                }

                return Ok("Thanks, I got your file ...");
            }
            catch (Exception ex)
            {
                return StatusCode(StatusCodes.Status500InternalServerError);
            }
        }

这是RequestModel.cs

    public class RequestModel
    {
        [JsonPropertyName("filename")]
        public string FileName { get; set; } = string.Empty;

        [JsonPropertyName("file")]
        public IFormFile? File { get; set; } = null;
    }
javascript google-chrome asp.net-core-webapi fetch-api
1个回答
0
投票

您遇到的第一个错误是因为浏览器自动将

Content-Type
设置为
multipart/form-data
,因此无需手动设置标题。 对于错误
RequestModel.File
为空,则表明服务器端未正确接收或解释文件。首先确保
JsonPropertyName
属性中的名称与您在 JavaScript 中的 FormData 对象中使用的键匹配。
chrome.tabs.captureVisibleTab
返回数据 URL,而不是 Blob。在将其附加到
formData
之前,您应该将其转换为 Blob。

您可以尝试以下代码:

async function TestPost() {
  const url = "https://localhost:7221/test/upload";

  const tabCapture = await chrome.tabs.captureVisibleTab();
  const blob = await (await fetch(tabCapture)).blob(); 

  const formData = new FormData();
  formData.append("filename", "my-file-name");
  formData.append("file", blob, "screenshot.jpg"); 

  fetch(url, {
    method: "POST",
    headers: {
      'Accept': 'application/json'
    },
    body: formData
  })
  .then(response => {
    if (!response.ok) {
      throw new Error(`HTTP error: ${response.status}`);
    }
    return response.json();
  })
  .then(data => {
    console.log(data);
  })
  .catch(error => console.log("ERROR - TestPost: " + error));
};
© www.soinside.com 2019 - 2024. All rights reserved.