【问题标题】:Sending a file with react dropzone and express multer使用 react dropzone 和 express multer 发送文件
【发布时间】:2025-12-07 07:05:01
【问题描述】:

使用 react-dropzone (http://okonet.ru/react-dropzone/) 我可以获取文件 onDrop。我正在使用 isomorphic-fetch 发送它们,但我无法正确获取 MIME 类型。

  onDrop(i, files) {
    console.log('Received files: ', i, files, files[0]);
    const file = files[0];

    apiCaller('box/upload/check', 'post', {
      fileData: {
        name: file.name,
        size: file.size,
        type: file.type,
        parent_folder_id: '11788814757',
      },
    }, {
      // 'content-type': 'text/plain',
    }).then((resp) => {
      console.log('upload check', i, files, typeof resp, resp, resp.ok);
      // if (err) {
      //   throw new Error('UPLOAD_CHECK_FAILED');
      // }


      if (resp.upload_url) {
        apiCaller('box/upload', 'post', null, {
          // 'Content-Type': 'multipart/form-data',
        }, {
          payload: file.preview,
          parent_folder_id: '11788814757',
        })
        .then((res, er) => {
          console.log('upload', i, files, res, er);
          if (res) {
            this.state.docsToBeUploaded[i].uploaded = true;
          }
        })
        .catch((e) => {
          console.error(e);
        });
      }
    })
    .catch((err) => {
      console.error(err);
    });
  }

这里是获取模块:

import fetch from 'isomorphic-fetch';
import Config from '../../server/config';

export const API_URL = (typeof window === 'undefined' || process.env.NODE_ENV === 'test') ?
  process.env.BASE_URL || (`http://localhost:${process.env.PORT || Config.port}/api`) :
  '/api';

export default function callApi(endpoint, method = 'get', body, headerConfig, isFormData = false) {
  console.log('calling API:', arguments);

  const defaultHeaders = {
    'Accept': 'application/json, application/xml, text/plain, text/html, *.*',
    'X-Requested-With': 'XMLHttpRequest',
  };
  const headers = { ...defaultHeaders, ...headerConfig };
  if (!isFormData) {
    headers['content-type'] = 'application/json';
  }
  console.log('headers', headers);
  return fetch(`${API_URL}/${endpoint}`, {
    credentials: 'include',
    headers,
    method,
    body: JSON.stringify(body),
  })
  .then(response => response.json().then(json => ({ json, response })))
  .then(({ json, response }) => {
    if (!response.ok) {
      return Promise.reject(json);
    }

    return json;
  })
  .then(
    response => response,
    error => error
  );
}

如果我手动设置 MIME 类型,则会遇到典型的“无边界”问题 (Error: Multipart: Boundary not found...),因为浏览器需要自行对其进行编码。

如果我不设置,则根本看不到文件...

我应该怎么做?我可以通过Postman实现上传,所以肯定是header配置...

编辑:仅供参考,我正在使用 https://www.npmjs.com/package/isomorphic-fetch 发送 xhr...

【问题讨论】:

    标签: reactjs mime-types dropzone.js


    【解决方案1】:

    您使用哪个库来上传文件,使用Request 非常简单。在 ondrop 方法中使用它

    【讨论】: