【问题标题】:how to upload images in flutter如何在颤动中上传图像
【发布时间】:2021-08-12 11:22:27
【问题描述】:

你好,我想在 Flutter 中上传图片

我尝试使用 http.MultipartRequest 像这样

  request.fields["name"] = "$RegisterName";
  request.fields["description"] = "$RegisterDescription";
  request.fields["caution"] = "$RegisterCaution";
  request.fields["price"] = "$RegisterPrice";
  request.fields["price_prop"] = "$RegisterPriceProp";
  request.fields["user.id"] = "1";
  request.fields["lend"] = "$RegisterCategory";
  request.fields["category"] = "Digital";
  request.fields["place_option"] = "true";

  var multipartFile = http.MultipartFile.fromBytes(
    'file',
    (await rootBundle.load('assets/images/main_1.jpg')).buffer.asUint8List(),
    filename: 'test01.jpg',
    contentType: MediaType('image', 'jpg'),
  );

  request.files.add(multipartFile);
  

  var response = await request.send();

  if (response.statusCode == 200) print('Upload');
}

但此代码不起作用 如果我使用此代码,请仅上传其他数据 upload things

那么json类型就是这个 json type image

我要上传图片文件...:(

【问题讨论】:

    标签: django flutter dart rest


    【解决方案1】:

    我用它来发送带有formData的图片

    var head = Api().bearerHeader; ////just bearerToken
    var request = http.MultipartRequest(
        'POST',
        Uri.parse(
            'https://c.....'));
    request.files
        .add(await http.MultipartFile.fromPath('TITLEOFFORMDATA', imageFile.path));
    request.headers.addAll(head);
    
    http.StreamedResponse response = await request.send();
    
    if (response.statusCode == 200) {
      String varo = await response.stream.bytesToString();
    }
    

    【讨论】:

      【解决方案2】:

      这是您可以使用MultipartRequesthttp 包将图像发送到服务器的方法

       try {
          final uri = Uri.parse(your_url);
      
          final request = http.MultipartRequest('POST', uri);
      
          final multipartFile =
              await http.MultipartFile.fromPath('Image', 'your_path_of_image'); // Image is the parameter name 
      
          request.files.add(multipartFile);
      
          request.fields['userId_if_required'] = value;
      
          final response = await request.send();
          if (response.statusCode == 200) {
            print('success');
          } else {
            print('Something went wrong');
          }
        } catch (e) {
          print('Something went wrong');
        }
      

      【讨论】:

      • 谢谢.. 但我还有另一个问题.... :( (OS Error: No such file or directory, errno = 2) 我能做什么..? 实际上我无法理解上传系统....
      • @Lily 您必须将您的资产图像转换为File 格式,请参考此链接stackoverflow.com/questions/55295593/…
      猜你喜欢
      • 2020-02-17
      • 1970-01-01
      • 2023-03-11
      • 2022-08-10
      • 2019-06-21
      • 2019-02-09
      • 1970-01-01
      • 2020-09-06
      • 1970-01-01
      相关资源
      最近更新 更多