5

我想用 html 文件将图像上传到strapi。当我运行代码时,我得到错误: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);
    }
});
4

3 回答 3

5

正如我所见,忘记添加 multipart/form-data

mimeType: "multipart/form-data"

您可以在此处查看文档

  1. 确保已使用 multipart/form-data 编码发送请求

  2. 允许的参数是:

    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.
    

单个文件请求

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

将文件链接到条目

例如,您在名为 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.
}
于 2018-10-07T21:23:22.117 回答
4

从今天开始,您可以使用 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)
}

我假设您有一个使用文件类型restaurant字段调用的集合image

更多信息在这里:https ://strapi.io/documentation/v3.x/plugins/upload.html#upload-files

于 2020-06-04T09:47:44.367 回答
0

RestRequest这是在带有 C# 的 Winforms 中使用的另一种方法:

var client = new RestClient("http://my-strapi-server:1337/upload");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddFile("files", @"C:\temp\bryan.jpg");
request.AddParameter("ref", "Singer");
request.AddParameter("refId", "605fe0c8sakhasg4c40253a");
request.AddParameter("field", "logo");
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
于 2021-03-28T12:37:40.460 回答