I'm facing a challenge where I need to transmit an image file from the frontend developed in Angular, along with additional parameters, using a POST request to my ASP.NET Core backend for file upload to a server. However, I'm encountering issues such as receiving an HTTP 500 Error based on the headers I set, or more commonly, the backend receiving an empty object when FormData is sent.
In my Angular code, I convert the Base64 image into a Blob, and then into a File to create the FormData object (this is the format returned by the ngx-compress-image package for image compression). I'm wondering if there might be a better approach to achieve this. After constructing the FormData object, I set the headers and initiate the POST request:
export class RestApiService {
token: string = 'The session token';
userID: string = 'The user ID';
UploadImage(picAsBase64: string) {
let blob = new Blob([picAsBase64], { type: 'image/png' });
let file = new File([blob], Math.random().toString(36).substr(2, 5));
let formData: FormData = new FormData();
formData.append('pfile', file);
const headers = new HttpHeaders({
'Content-Type': 'multipart/form-data',
'Accept': 'application/json'
});
let options = { headers: headers };
let body = {
'paramh': this.token,
'pfile': formData,
'pkuserid': this.userID
}
return this.http.post('api/UploadFiles/UploadFiles/', body, options).pipe(map(data => { return data; }));
}
}
Backend:
[Route("api/[controller]")]
public class UploadFilesController : Controller
{
[HttpPost("UploadFiles")]
public async Task<IActionResult> UploadFiles([FromBody]JObject data)
{
string paramh = data["paramh"].ToString();
IFormFile pfile = data["pfile"].ToObject<IFormFile>();
string pkuserid = data["pkuserid"].ToString();
...
}
}
EDIT I followed Tony's solution, but initially encountered issues. After some experimentation, I found success by declaring the IFormFile variable as a List as suggested by Nishant and using [FromForm] for each argument, like this:
public async Task<IActionResult> UploadFiles([FromForm]string paramh, [FromForm] string pkuserid, [FromForm]List<IFormFile> pfiles)
However, I'm facing another problem where my IFormFile has the ContentType set as application/octet-stream. I'm unsure if this is standard behavior and if I need to convert it to an image content type on the backend, or if it should be received in the POST request as image/png, as declared in the Angular Blob before creating the file.
Thank you all for your help, and I'm hopeful that you can assist me in resolving this final issue.