【问题标题】:Unable to upload file using FormData to express server from react application无法使用 FormData 上传文件以从反应应用程序表达服务器
【发布时间】:2021-04-02 05:24:22
【问题描述】:

我无法使用来自 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 = "";
};

postFile.ts 中的 console.log 仅显示“用户名:Sparsha Saha”

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

【问题讨论】:

    标签: reactjs express axios multipartform-data form-data


    【解决方案1】:

    看起来,console.log 没有显示该文件,但它肯定会上传到指定的文件夹。我想知道文件数据实际附加到请求的哪一部分,以及我们是否可以以某种方式对其进行可视化。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-11-09
      • 2013-06-15
      • 1970-01-01
      • 2022-01-21
      • 2019-01-25
      • 1970-01-01
      • 2019-01-14
      相关资源
      最近更新 更多