axios 为什么我的req.files总是null而req.body有这个文件:用express-fileuload/reactjs上传文件

polkgigr  于 2023-03-02  发布在  iOS
关注(0)|答案(2)|浏览(134)

我需要你的帮助我找不到错误我尝试使用express-fileupload在代码中上传一个文件,但是在nodemon中req.files总是空的:files:null但我发现我的file属性传递到req.body,如下所示:正文:{文件:'[object File]' }我尝试用RESTer测试我的URL,文件上传成功,但我的响应输入不起作用。我尝试了过去4天的很多事情,但我仍然没有找到我的错误在哪里,是在formData中吗??* 请帮助我 *

这是我的前端React代码:

import Message from './Message';
import Progress from './Progress';
import axios from 'axios';

const FileUpload = () => {
  const [file, setFile] = useState('');
  const [filename, setFilename] = useState('Choose File');
  

  const onChange = e => {
      console.log(e.target.files[0].name)
    setFile([e.target.files[0]]);
    setFilename(e.target.files[0].name);
    
  };
 
  const onSubmit = async e => {
    
    const formData = new FormData(); 
    formData.append("file", file);
   
  if(!formData){
   console.log("empty");}
  
  
    try {
        const res = await axios.post('http://localhost:5001/up', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
        
      });
      console.log("file read");
     
      console.log(res)
      const { fileName, filePath } = res.data;
    
    } catch (err) {
     console.log(err)
      
    }
  };

  return (
    <Fragment>
     
      <form onSubmit={onSubmit} enctype='multipart/form-data'>
        <div className='custom-file mb-4'>
          <input
            type='file' 
            enctype='multipart/form-data'
            className='custom-file-input'
            id='customFile'
            onChange={onChange}
          />
          <label className='custom-file-label' htmlFor='customFile'>
            {filename}
          </label>
        </div>

        <input
          type='submit'
          value='Upload'
          className='btn btn-primary btn-block mt-4'
        />
      </form>
     
    </Fragment>
  );
};

export default FileUpload;

还有后端:

import cors from "cors"
import nez_topographie from "./api/controllers/nez_topographie.route.js"
import fileUpload from "express-fileupload"
import multer from "multer"
import bodyParser from "body-parser"
import morgan from "morgan"

const app = express()
app.use(fileUpload({
    createParentPath: true
  }))
app.use(cors())
app.use(express.json())
app.use(express.urlencoded({ extended: true }))
app.use(morgan("dev"))



app.use("/nez_topographie", nez_topographie)

app.post('/up', async (req, res) => {
    try {
        console.log(req)
        
        
        if(!req.files) {
            console.log("no")
            res.send({
                status: false,
                message: 'No file uploaded'
            });
        } else {
            //Use the name of the input field (i.e. "avatar") to retrieve the uploaded file
            let avatar = req.files.file;
            
            //Use the mv() method to place the file in upload directory (i.e. "uploads")
            avatar.mv('./' + avatar.name);

            //send response
            res.send({
                status: true,
                message: 'File is uploaded',
                data: {
                    name: avatar.name,
                    mimetype: avatar.mimetype,
                    size: avatar.size
                }
            });
        }
    } catch (err) {
        console.log(err)
        res.status(500).send(err);
    }
});

export default app
gwo2fgha

gwo2fgha1#

我刚刚遇到了同样的问题。我必须在前端向我的FormData示例添加一个文件名。

const formData = new FormData(); 
formData.append("file", file, "myfile.txt");

如果需要,也可以像这样传递原始文件名

formData.append("file", file, file.name);
blmhpbnm

blmhpbnm2#

我的解决方案:试试看

formData.append('file', {
        uri: file[0].uri,
        type: file[0].type,
        name: file[0].fileName
    })

代替

formData.append("file", file);

相关问题