我正在尝试使用FormData和Dio发送一个巨大的图像,服务器端是用NodeJS编写的
每当我发送一个1 MB或更少的图像时,它工作得很好,但我尝试发送一个17 MB大小的图像,应用程序滞后了一段时间,然后退出
这是颤振代码
Future<Uint8List> _convertImageToUint8List(final String imagePath) async {
ByteData imageByteDate = await rootBundle.load(imagePath);
ByteBuffer imageBuffer = imageByteDate.buffer;
return imageBuffer.asUint8List();
}
void _testUploadingImageWithDio(
{final String ip,
final String port,
final String api,
final String imagePath}) async {
Dio dio = new Dio();
Uint8List imageUint8List = await _convertImageToUint8List(imagePath);
FormData formData = new FormData.fromMap({
'image': imageUint8List,
});
String url = 'http://$ip:$port/$api';
print('URL: $url}');
var response = await dio.post(url, data: formData);
print('response: $response');
}
除了我在颤振MultipartRequest中尝试了另一个类,但是图像的大小增加了一倍,我的意思是17 MB的图像到达了大小为32 MB的服务器并且图像已损坏。
这是代码
void _testUploadingImageWithMultiPartRequest(
{final String ip,
final String port,
final String api,
final String imagePath}) async {
// Constructing the request
Uri postUri = Uri.parse('http://$ip:$port/$api');
print('URI ${postUri.toString()}');
http.MultipartRequest request = new http.MultipartRequest("POST", postUri);
// request.fields['user'] = 'someone@somewhere.com';
// Loading the image from image path using root bundle
// convert it to buffer and uint8 list
// append it to the request
Uint8List imageUint8List = await _convertImageToUint8List(imagePath);
http.MultipartFile imageToBeSent = new http.MultipartFile.fromBytes(
'image', imageUint8List,
contentType: new MediaType('image', 'png'));
request.files.add(imageToBeSent);
// Sending the request
request.send().then((response) {
if (response.statusCode == 200) print("Uploaded!");
}).catchError((onError) {
print(onError);
});
}
对于服务器端应用程序,我正在执行以下操作
const upload = multer({storage: storage, fileFilter: fileFilter, limits: {fieldSize: 200 * 1024 * 1024}});
app.post('/upload', upload.single('image'), (req, res) => {
const buffer = Buffer.from(req.body['image']);
fs.writeFileSync('./some_image', buffer);
try {
return res.status(200).json({
message: 'File uploded successfully'
});
} catch (error) {
console.error(error);
}
});
编辑
对于 17 MB 图像
对于损坏的,在服务器端
对于工作正常的小图像