-1

我在反应中找到了一个简单的图像上传器。该软件包通过简单的点击上传文件。有没有办法以表单形式获取上传文件的 url,以便我可以在带有用户 ID 的表中插入图像 url

反应图像上传器

服务器端代码

app.post('/multiple', upload.array('file'), function (req, res) {
const photos = req.files;
let data = [];
photos.map(p => data.push({
  name: `${API_URL}/uploads/${p.filename}`,
  orginal_name: `${p.originalname}`
}));
res.send({
  status: true,
  message: 'Photos are uploaded.',
  data: data
});
});

我正在尝试在节点中使用 multer。但它可以与这个包一起使用吗?我应该如何获得“文件”,因为这里没有名称文件的输入。感谢帮助

前端代码

 <ImagesUploader
                url="http://localhost:5000/multiple"
                optimisticPreviews
                multiple={true}
                onLoadEnd: function(error: { message: string, ... }, response?: JSON)
                label="Upload a picture"
                />

它输出以下错误

  Line 283:36:  Parsing error: Unexpected token

  281 |                 optimisticPreviews
  282 |                 multiple={true}
> 283 |                 onLoadEnd: function(error: { message: string, ... }, response?: JSON)
      |                                    ^
  284 |                 label="Upload a picture"
  285 | 
  286 | 

并且

Access to fetch at 'http://localhost:5000/multiple' from origin 'http://localhost:3000' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.

由于 CORS 错误发生,它无法检查我收到的响应

app.use(cors());
app.options('*', cors());

我评论了节点中的第二行并只允许' http://localhost:3000 '但仍然是同样的错误

4

1 回答 1

0

正如我从这个库的描述中看到的,它取决于你的服务器。当您在服务器上处理上传时,您可以返回新文件的 url 和任何其他数据。您可以在回调中接收此数据

onLoadEnd: function(error: { message: string, ... }, response?: JSON)

它们将存储在“响应”中

代码可能是下一个:

上传回调(如果您使用挂钩)。

const loadEnd = (error, response) => {
  if (!error) {
    const data = JSON.parse(response)
    // Here you can handle your data and save it to state. 
    // And after read it from state in function render().
  }
}

您渲染要上传的元素。

<ImagesUploader
  url="http://localhost:5000/multiple"
  optimisticPreviews
  multiple={true}
  onLoadEnd: {loadEnd}
  label="Upload a picture"
  />
于 2020-01-16T04:45:21.067 回答