簡體   English   中英

如何將表單數據從 javascript 發送到 web api 作為 IFormFile

[英]How to send form data from javascript to web api as IFormFile

I'm trying to send request with pdf file to test API, I trigger method from JavaScript which is executing method on .net core web api.

我的朋友剛剛給我發了一張來自 postman 的截圖我應該創建什么樣的請求:

在此處輸入圖像描述

根據這張圖片,我發現我需要像這樣創建發布請求:

{
  "access_name": "employee",
  "product":"{\"product_id\":\"\",\"group_id\":\"1\",\"subgroup_id\":\"\",\"employee_id\":\"28\"}"
  "product_document": { // File }
}

從 postman 我意識到它是文件類型,所以我想知道如何將帶有其他信息的文件類型發送到我的服務器。

這是我的前端代碼:

let f = new FormData();
f.append('File', file);
f.append('DocumentType', file.documentType);

objectToSend = {
    ...values,
    document: f,
};


await createProduct(objectToSend);

export const createProduct = async data => {
  return axiosWrapper.request({
    url: `/products`,
    method: 'POST',
    data: data,
  });
};

這是它在服務器上的外觀:

// POST: api/products
[HttpPost]
public async Task<IActionResult> Post(Product objectToCreate)
{
 // Create product
}

我的產品 class 包含 IFile 我應該在其中保存文件..

  // Dont worry about props name as I map them somewhere in the middle
  public class Product
    {
        public long Id { get; set; }
        public string ProductTitle{ get; set; }
        public string Brand { get; set; }
        public string ProductType { get; set; }
        public IFormFile Document { get; set; } // Here I wanted to receive doc as IFormFile but this wont work
    }

但這不起作用,因為我一直收到不好的請求,因為我不知道如何從前端發送 IFormFile ..

這是 postman 將為您生成的內容:

var form = new FormData();
form.append("", "yourfile.pdf");

var settings = {
  "async": true,
  "crossDomain": true,
  "url": "https://",
  "method": "POST",
  "headers": {},
  "processData": false,
  "contentType": false,
  "mimeType": "multipart/form-data",
  "data": form
}

$.ajax(settings).done(function (response) {
  console.log(response);
});

這段代碼並不完美,但這很容易上手

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM