提供一些其他的解决方案;我们也在使用react-native-image-picker
;并且服务器端正在使用koa-multer
;此设置运行良好:
用户界面
ImagePicker.showImagePicker(options, (response) => {
if (response.didCancel) {}
else if (response.error) {}
else if (response.customButton) {}
else {
this.props.addPhoto({ // leads to handleAddPhoto()
fileName: response.fileName,
path: response.path,
type: response.type,
uri: response.uri,
width: response.width,
height: response.height,
});
}
});
handleAddPhoto = (photo) => { // photo is the above object
uploadImage({ // these 3 properties are required
uri: photo.uri,
type: photo.type,
name: photo.fileName,
}).then((data) => {
// ...
});
}
客户
export function uploadImage(file) { // so uri, type, name are required properties
const formData = new FormData();
formData.append('image', file);
return fetch(`${imagePathPrefix}/upload`, { // give something like https://xx.yy.zz/upload/whatever
method: 'POST',
body: formData,
}
).then(
response => response.json()
).then(data => ({
uri: data.uri,
filename: data.filename,
})
).catch(
error => console.log('uploadImage error:', error)
);
}
服务器
import multer from 'koa-multer';
import RouterBase from '../core/router-base';
const upload = multer({ dest: 'runtime/upload/' });
export default class FileUploadRouter extends RouterBase {
setupRoutes({ router }) {
router.post('/upload', upload.single('image'), async (ctx, next) => {
const file = ctx.req.file;
if (file != null) {
ctx.body = {
uri: file.filename,
filename: file.originalname,
};
} else {
ctx.body = {
uri: '',
filename: '',
};
}
});
}
}