So to be more specific, I created a C# API. It works nice, I can call requests in any controller fine. But when it comes to sending a POST request to upload two files it says bad request, error 400 and just stops.
Here is the code of the API
[HttpPost]
public async Task<IActionResult> CreateBook([FromForm]IFormFile cover, [FromForm]IFormFile file, [FromForm]string title, [FromForm]string metaData, [FromForm]string description, CancellationToken cancellationToken)
{
if (cover == null || file == null)
{
return BadRequest();
}
await using var stream = new MemoryStream();
await file.CopyToAsync(stream);
var id = Guid.NewGuid();
var fileExt = Path.GetExtension(file.FileName);
var coverExt = Path.GetExtension(cover.FileName);
var docName = $"{id}{fileExt}";
var coverName = $"{id}{coverExt}";
var bookDoc = new S3Obj()
{
BucketName = Constants.bucketName,
InputStream = stream,
Name = Constants.bookPath + docName
};
var bookCover = new S3Obj()
{
BucketName = Constants.bucketName,
InputStream = stream,
Name = Constants.bookCoverPath + docName
};
var cred = new Credentials()
{
AccessKey = Constants.accessKey,
SecretKey = Constants.secretKey
};
var docResponse = await StorageService.Singleton.UploadFileAsync(bookDoc, cred);
var coverResponse = await StorageService.Singleton.UploadFileAsync(bookCover, cred);
Console.WriteLine(docResponse.Message);
Book book = new Book() { Id = id, Title = title, MetaData = metaData, Description = description, Cover = coverName, DocumentPath = docName };
return Ok(await Mediator.Send(new CreateBook.Command() { Book = book }, cancellationToken));
}
Then this code is called from a React app in fetch, with the following:
const sendRequest = () => {
var base = process.env.REACT_APP_API_URL;
var data = new FormData();
data.append('cover', cover);
data.append('file', file);
data.append('title', title);
data.append('metaData', meta);
data.append('description', description);
fetch(base + "/Book",{ method: 'POST', body: data, headers:{'Content-Type':'multi-part/formdata'} }).then(succes => { console.log(succes); console.log(data); window.location.reload() }).catch(e => {console.log(e); console.log(data);});
}
I am stuck with this and I have to finish it fast, but I just can't get it to work, I am not really great at frontend. I also tried passing other parameters in the url, instead of formdata and leaving only the 2 files in formdata, but there was no change.
I am appreciating any help, thanks in advance.