无法使用 FormData 上传文件以从 React 应用程序表达服务器

Unable to upload file using FormData to express server from react application

我无法使用来自 React 应用程序的 axios 使用 FormData 上传文件来表达使用 multer 的服务器。

附加在 formData 中的文本数据显示在服务器上,但任何文件似乎在服务器端都不可见。

虽然在客户端探索 formData 键显示了文件。

这是我用于打印正文内容的服务器代码: postFile.ts

import * as path from 'path';

let multer = require("multer");
let storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, path.resolve(__dirname));
    },
    filename: function (req, file, cb) {
        cb(null, file.originalname);
    }
});

let upload = multer({ storage: storage });
export const postFile = (app: IApp) => {
    app.post('/uploadFile', upload.any(), (request: IRequest, response: IResponse) => {
        console.log('Got body:', JSON.stringify(request.body));
        response.sendStatus(200);
    });
}

这是 React 客户端代码: filePicker.tsx

import axios from "axios";
import * as React from "react";
interface IFilePickerProps {
  fileToUpload: File;
  setFileToUpload: React.Dispatch<File | undefined>;
}

export const FilePicker = (props: IFilePickerProps) => {
  const { setFileToUpload, fileToUpload } = props;

  // Ref to input element to reset value on file upload completion
  const inputRef = React.useRef<HTMLInputElement>();

  const { onFileUpload, onFileChange } = useUploadFileCallbacks(
    setFileToUpload,
    fileToUpload,
    inputRef
  );

  return (
    <>
      <label>
        <input type="file" onChange={onFileChange} ref={inputRef} />
      </label>
      <button onClick={onFileUpload}>Upload File</button>
    </>
  );
};

const useUploadFileCallbacks = (
  setFileToUpload: React.Dispatch<File | undefined>,
  fileToUpload: File,
  inputRef: React.RefObject<HTMLInputElement>
) => {
  const onFileChange = React.useCallback(
    (event: React.ChangeEvent<HTMLInputElement>) => {
      setFileToUpload(event.target.files[0]);
    },
    [setFileToUpload]
  );

  const onFileUpload = React.useCallback(() => {
    handleFileUpload(fileToUpload, inputRef);
  }, [fileToUpload]);

  return { onFileChange, onFileUpload };
};

const handleFileUpload = async (
  fileToUpload: File,
  inputRef: React.RefObject<HTMLInputElement>
) => {
  let formData = new FormData();
  formData.append("usernamesss", "Sparsha Saha");
  formData.append("file", fileToUpload);
  axios
    .post("http://localhost:3001/uploadFile", formData, {
      headers: {
        "content-type": "multipart/form-data",
      },
    })
    .then(() => {
      console.log("Complete");
    });
  inputRef.current.value = "";
};

console.log中的postFile.ts只显示'usernamesss: Sparsha Saha'

我四处寻找解决方案,但似乎没有什么适合我的。有人可以帮我吗?

好像,console.log 没有显示文件,但肯定会上传到指定的文件夹。我想知道文件数据实际附加到请求的哪一部分,以及我们是否可以通过某种方式将其可视化。