使用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实现上传,所以它肯定是标题配置...
编辑:仅供参考我正在使用https://www.npmjs.com/package/isomorphic-fetch发送xhr ...