【问题标题】:flutter file http request颤振文件http请求
【发布时间】:2021-06-22 10:11:08
【问题描述】:

你好,我正在尝试使用 JSON 和文件一起进行发布请求,应该如何

static Future postApost(String posttitle,image,String value,token) async {
var data = {'posttitle': posttitle, 'post': image.readAsBytes(),'category': value};
await http.post("https://lighte.org/public/api/newpost",headers: {
  'Authorization': 'bearer $token',
},body: data).catchError((error) {
 print(error.toString());
});

 }

【问题讨论】:

    标签: flutter http multipart


    【解决方案1】:
    static Future postApost(String posttitle,image,String value,token) async {
    
    var request = http.MultipartRequest(
          'POST', Uri.parse("https://lighte.org/public/api/newpost"));
    
    //**fromPath()** method is used when you are sending an image from a specific path,
    //inCase of String byte Images you have to use the preferred method in MultipartFile class
    
      await http.MultipartFile.fromPath(
        'image',
        image.path,//use can pass file path here
        filename: 'image_name.jpg',
      );
       request.fields['posttitle'] = posttitle;
    request.fields['category'] = value;
    request.headers["Authorization"] = 'bearer $token';
    
    
    
     }
    

    【讨论】:

      【解决方案2】:
      uploadUserImg (
        String filename, String url, File img, String token
                         ) async {
      
            //URI with type of request (POST or GET ...)  ---------------
            var request = http.MultipartRequest('POST', Uri.parse(url));
      
      
          //Header type with access token    ------------------------
            request.headers.addAll({
              "Content-Type": "application/json",
              'Authorization': 'Bearer $token ',
            });
      
      
          //adding  body parameter for request   -----------------------
          // you can remove this it will not affect the code
            request.fields.addAll({
               
              'phone_number': '+201097081508'
            });
            
      
        // adding File image     -------------------------------
         request.files.add(
      http.MultipartFile.fromBytes('image_endpoint', img.readAsBytesSync(),
                filename: filename));
              
        //send request + listing to its response  
             request.send().then(
              (response) {
      
              //parsing the response to print it 
               response. stream.transform(utf8.decoder).listen(
      (responseString) {
              print(responseString);
              });  
      
          }
      

      【讨论】:

      • request.fields.addAll 通过这种方法我们可以在 Map 中获取数据。如果数据 (body) 在 Map 中怎么办?
      • 因此将您的 Map 解析为字符串,然后在返回时将您的 String 解析为 Json,然后再进行映射
      猜你喜欢
      • 2020-11-09
      • 2021-07-04
      • 2021-02-23
      • 2020-06-18
      • 2019-12-19
      • 1970-01-01
      • 2018-06-21
      • 2020-11-10
      • 2020-07-06
      相关资源
      最近更新 更多