将图片上传到 Strapi

cal*_*one 5 javascript strapi

我想用 html 文件将图像上传到 Strapi。运行代码时,出现错误:POST http://localhost:1337/upload 500(内部服务器错误)。

$.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);
    }
});
Run Code Online (Sandbox Code Playgroud)

xar*_*rgr 5

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

mimeType: "multipart/form-data"
Run Code Online (Sandbox Code Playgroud)

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.
    
    Run Code Online (Sandbox Code Playgroud)

Single file request

curl -X POST -F 'files=@/path/to/pictures/file.jpg' http://localhost:1337/upload
Run Code Online (Sandbox Code Playgroud)

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.
}
Run Code Online (Sandbox Code Playgroud)


ale*_*lli 5

从今天开始,您可以使用带有以下代码的 axios 将文件上传到 Strapi。这是文件输入上的输入事件的处理程序。

onInput (files) {
  const axios = require('axios')

  const STRAPI_BASE_URL = 'http://localhost:1337'

  const formData = new FormData()
  formData.append('files', files)
  formData.append('ref', 'restaurant') // optional, you need it if you want to link the image to an entry
  formData.append('refId', 12345) // optional, you need it if you want to link the image to an entry
  formData.append('field', 'image') // optional, you need it if you want to link the image to an entry

  axios.post(`${STRAPI_BASE_URL}/upload`, formData)
}

Run Code Online (Sandbox Code Playgroud)

我假设您有一个名为文件类型restaurant字段image的集合。

更多关于这里:https : //strapi.io/documentation/v3.x/plugins/upload.html#upload-files