【问题标题】:how to upload image to rest API in flutter through http post method?如何通过http post方法将图像上传到rest API?
【发布时间】:2019-12-28 09:51:49
【问题描述】:

我正在尝试通过 post 方法通过颤振上传图像。我正在使用 image_picker 从手机中挑选文件,但我无法上传

我已经尝试发送 FormData 之类的文件也不起作用

      Future<dynamic> uploadLicence(int id ,dynamic obj) async {
          FormData formdata = new FormData(); // just like JS
          formdata.add("image",obj); 
          final response = await post('Logistic/driver/LicenceImage? 
          driverId=$id', 
          formdata);
          print(response);
         //  return null;
     if (response.statusCode == 200) {
         final result = json.decode(response.body);
         return result;
    } else {
          return null;
   }
   }

在那之后,我只是尝试了这种方法,但这也不起作用

   Future<dynamic> uploadLicence(int id, File file) async {
   final url = Uri.parse('$BASE_URL/Logistic/driver/LicenceImage? 
   driverId=$id');
   final fileName = path.basename(file.path);
   final bytes = await compute(compress, file.readAsBytesSync());

   var request = http.MultipartRequest('POST', url)
   ..files.add(new http.MultipartFile.fromBytes(                                                     
  'image',bytes,filename: fileName,);
  var response = await request.send();
  var decoded = await 
  response.stream.bytesToString().then(json.decode);
  if (response.statusCode == HttpStatus.OK) {
  print("image uploded $decoded");
  } else {
   print("image uplod failed ");
  }
  }

             List<int> compress(List<int> bytes) {
             var image = img.decodeImage(bytes);
             var resize = img.copyResize(image);
            return img.encodePng(resize, level: 1);
            }

【问题讨论】:

  • 你得到什么错误?你打印了decoded 变量吗?
  • @ Esen Mehmet before decoded 我收到此错误未处理异常:无效参数:隔离消息中的非法参数:(对象是一个闭包 - 函数“压缩”:.)
  • 改变这个:compute(compress, file.readAsBytesSync()) => compute(compress(), file.readAsBytesSync())。您正在使用 compress 方法作为参考,而不是使用它的返回值。
  • 当我通过 compress() 时显示错误 compress(List&lt;int&gt; bytes) → List&lt;int&gt; The argument type 'List&lt;int&gt;' can't be assigned to the parameter type '(List&lt;int&gt;) → FutureOr&lt;dynamic&gt;
  • 我认为问题在于bytes 变量。你可以尝试用这个函数替换bytes 变量吗? compress(await file.readAsBytesSync())我必须模拟这个才能给出精确的解决方案。

标签: flutter dart


【解决方案1】:

MultipartRequest 可以。或者您可以简单地使用dio 包。这是一个命令。

用http:

import 'package:http/http.dart' as http;

final Uri uri = Uri.parse(url);
final http.MultipartRequest request = http.MultipartRequest("POST", uri);
// Additional key-values here
request.fields['sample'] = variable;
// Adding the file, field is the key for file and file is the value
    request.files.add(http.MultipartFile.fromBytes(
        field, await file.readAsBytes(), filename: filename);
// progress track of uploading process
final http.StreamedResponse response = await request.send();
print('statusCode => ${response.statusCode}');
// checking response data
Map<String, dynamic> data;
await for (String s in response.stream.transform(utf8.decoder)) {
  data = jsonDecode(s);
  print('data: $data');
}

【讨论】:

  • @Jey 你能分享你的例子吗?
  • 我在我的问题中添加了一个示例
【解决方案2】:

我将此代码用于我的项目,希望对您有用

Upload(File imageFile) async {    
var stream = new http.ByteStream(DelegatingStream.typed(imageFile.openRead()));
  var length = await imageFile.length();

  var uri = Uri.parse(uploadURL);

 var request = new http.MultipartRequest("POST", uri);
  var multipartFile = new http.MultipartFile('file', stream, length,
      filename: basename(imageFile.path));
      //contentType: new MediaType('image', 'png'));

  request.files.add(multipartFile);
  var response = await request.send();
  print(response.statusCode);
  response.stream.transform(utf8.decoder).listen((value) {
    print(value);
  });
}

【讨论】:

    猜你喜欢
    • 2012-07-24
    • 2020-09-08
    • 1970-01-01
    • 1970-01-01
    • 2021-05-09
    • 2016-02-21
    • 2017-06-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多