[英]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. 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.
My friend just sent me an screenshot from postman what kind of request I should create:我的朋友刚刚给我发了一张来自 postman 的截图我应该创建什么样的请求:
Based on this image I figure out that I need to create post request like this:根据这张图片,我发现我需要像这样创建发布请求:
{
"access_name": "employee",
"product":"{\"product_id\":\"\",\"group_id\":\"1\",\"subgroup_id\":\"\",\"employee_id\":\"28\"}"
"product_document": { // File }
}
From the postman I realized it's file-type, so I'm wondering how could I send file type with other informations to my server.从 postman 我意识到它是文件类型,所以我想知道如何将带有其他信息的文件类型发送到我的服务器。
Here is my frontend code:这是我的前端代码:
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,
});
};
Here's how it looks on the server:这是它在服务器上的外观:
// POST: api/products
[HttpPost]
public async Task<IActionResult> Post(Product objectToCreate)
{
// Create product
}
And my Product class which is containg IFile where I should kept file..我的产品 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
}
But this is not working, since I'm getting bad request all the time because obliviously I don't know how to send IFormFile from frontend..但这不起作用,因为我一直收到不好的请求,因为我不知道如何从前端发送 IFormFile ..
This is something that postman will generate for you:这是 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);
});
This code is not perfect but this is pretty simple to start with这段代码并不完美,但这很容易上手
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.