Reputation: 47
I'm trying to upload a file. I've got it to the server and I can see it. The code I'm using to post is
postTheFileToStrapi2(file: File) {
const formData: FormData = new FormData();
console.log(file[0].name);
formData.append('file', file[0]);
this.http.post('http://localhost:1337/upload', formData)
.subscribe((response) => console.log(response));
}
The problem is, I get an error of:
{
"statusCode":400,
"error":"Bad Request",
"message":[
{"messages":[
{"id":"Upload.status.empty","message":"Files are empty"}
]}]}
But, looking at the headers in Chrome, I am sending this:
Any pointers would be greatly received.
Upvotes: 1
Views: 4002
Reputation: 415
you can follow below example to upload image in Angular.
in your .HMTL file in your HTML file do like this
<input class="hidden" type="file" (change)="readURL($event);" name="Uploadfile"
id="file" style="width: 100%;cursor: pointer;" #fileInput>
Declare fileInput variable like below in component.ts file
@ViewChild('fileInput', { static: false }) fileInput: ElementRef;
you can try like this in component.ts
uploadPhoto() {
let userid = "43345;
var nativeElement: HTMLInputElement = this.fileInput.nativeElement;
var file = nativeElement.files[0];
nativeElement.value = '';
this.sampleService.ImageUpload(userid, file)
.subscribe(photo => {
,
err => {
});
}
in service file do like below
ImageUpload(id, file) {
var formData = new FormData();
formData.append('file', file);
return this.Http.post(this.url+ 'ImageUpload' + '/' + id, formData);
}
in WEB API do like below code to receive file from Angular
[HttpPost("ImageUpload/{Id}")]
public async Task<IActionResult> plantFileUpload(string Id, [FromForm(Name = "file")] IFormFile file)
{
}
This should work
Upvotes: 0
Reputation: 114
Try to replace
formData.append('file', file[0]);
with
formData.append('files', file[0]);
--> plural instead of singular. As far as I understand the strapi api (or upload plugin?) expects the data to be in a field named "files".
I struggled for hours until I read Pavlo Razumovskyi's comment here:
It's new api now, check new docs: strapi.io/documentation/3.0.0-beta.x/plugins/… formData.append('files.MODEL_FILE_FIELD_NAME', blob, filename)
That solved it for me at least!
Upvotes: 6