颤振文件http请求

时间:2021-06-22 10:11:08

标签: flutter http multipart

你好,我正在尝试使用 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());
});

 }

2 个答案:

答案 0 :(得分:0)

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';



 }

答案 1 :(得分:0)

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);
        });  

    }