Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Upload image to strapi

I would like to upload an image to strapi with a html file. When I run the code, I obtain the error: POST http://localhost:1337/upload 500 (Internal Server Error).

$.ajax({
    type: 'POST',
    url: 'http://localhost:1337/upload',
    datatype: 'image/jpeg',
    data: JSON.stringify(img),
    complete: function(product) {
        console.log('Congrats, your product has been successfully created: ', product.description);
    },
    fail: function(error) {
        console.log('An error occurred:', error);
    }
});
like image 935
calzone Avatar asked Aug 07 '18 08:08

calzone


People also ask

How do you put a picture on a Strapi?

Upload entry files The folder where the file(s) will be uploaded to (only supported on strapi-provider-upload-aws-s3). The ID of the entry which the file(s) will be linked to. The unique ID (uid) of the model which the file(s) will be linked to (see more below). The name of the plugin where the model is located.

Does Strapi optimize images?

By default, the Strapi Media Library will enable size optimization without quality loss and multiple responsive formats (small, medium and large). Simply go to settings to enable these options and make your images work across many devices and channels.


1 Answers

As I can see forgetting to add multipart/form-data

mimeType: "multipart/form-data"

You can see documentation here

  1. Ensure that have send the request using multipart/form-data encoding

  2. The parameters allowed are:

    files: The file(s) to upload. The value(s) can be a Buffer or Stream.
    
    path: (optional): The folder where the file(s) will be uploaded to (only supported on strapi-upload-aws-s3 now).
    
    refId: (optional): The ID of the entry which the file(s) will be linked to.
    
    ref: (optional): The name of the model which the file(s) will be linked to.
    
    source: (optional): The name of the plugin where the model is located.
    
    field: (optional): The field of the entry which the file(s) will be precisely linked to.
    

Single file request

curl -X POST -F 'files=@/path/to/pictures/file.jpg' http://localhost:1337/upload

Linking files to an entry

For example that you have link image field in User model named avatar

{
 "files": "...", // Buffer or stream of file(s)
 
 "path": "user/avatar", // Uploading folder of file(s).
 
 "refId": "5a993616b8e66660e8baf45c", // User's Id.
 
 "ref": "user", // Model name.
 
 "source": "users-permissions", // Plugin name.
 
 "field": "avatar" // Field name in the User model.
}
like image 79
xargr Avatar answered Oct 03 '22 14:10

xargr