我收到 400 代码的“文件为空”

问题描述 投票:0回答:1

我正在尝试将图像上传到strapi,我在这里做错了什么?我是否将

fileArrayForUpload
放错了位置?
fileArrayForUpload
不为空。

处理创建提交:

 const [createProduct] = useMutation(CREATE_PRODUCT);

   const handleCreateSubmit = useCallback(async () => {

      const res = await HTTP_CLIENT.post('/api/upload', fileArrayForUpload);
      console.log(res);
      await createProduct({
         variables: {
            data: {
               reference: reference,
               description: description,
               price: {
                  displayPrice: currency,
                  numericPrice: numericPrice,
               },
               category: selectedCategory,
            },
         },
         onCompleted: handleSucessSubmit,
         onError: handleErrorSubmit,
      });
   }, [
      reference,
      description,
      currency,
      numericPrice,
      selectedCategory,
      fileArrayForUpload,
   ]);  

我输入的代码:

 <input
                  ref={inputRef}
                  accept="image/*"
                  type="file"
                  multiple
                  id="select-image"
                  style={{ display: 'none' }}
                  onChange={(e) => {
                     if (!e.target.files) return;
                     const selectedFiles = Array.from(e.target.files);
                     const dataUrls = selectedFiles.map((file) =>
                        URL.createObjectURL(file),
                     );
                     setFileArrayForUpload(Array.from(e.target.files));
                     console.log(fileArrayForUpload);
                     setImageUrlArray((prevImages) => [...prevImages, ...dataUrls]);
                  }}
               />
               <label htmlFor="select-image">
                  <IconButton color="primary" component="span">
                     <FileUploadIcon fontSize="large" />
                  </IconButton>
               </label>

我希望上传图像,但收到错误 400“文件为空”,这对我来说没有意义。

reactjs node.js arrays rest graphql
1个回答
0
投票

上传时需要将文件以form格式附上。

const imgFile = event.target.files[0];
var formData = new FormData();
formData.append('files', imgFile, imgFile.name);

axios.post(url, formData).then(res => {
  console.log(res);
}).catch(error =>{
  console.log(error.message);
});

将图像上传到 Strapi /使用 axios 和 React 上传

在管理面板中上传文件时,您可以在网络浏览器中检查网络负载

© www.soinside.com 2019 - 2024. All rights reserved.