我想添加头部与access_token为Flutter上传图像

z9gpfhce  于 2023-05-23  发布在  Flutter
关注(0)|答案(3)|浏览(141)

我的API需求为

URL: /user/upload-profile-image

method= POST

header--

Accesstoken: "access_token"

content-type = multipart/form-data

这是我的代码:

Future getUploadImg(File _image) async {

  String apiUrl = '$_apiUrl/user/upload-profile-image';

  final length = await _image.length();

  final request = new http.MultipartRequest('POST', Uri.parse(apiUrl))
      ..files.add(new http.MultipartFile('avatar', _image.openRead(), length));

  http.Response response = await http.Response.fromStream(await request.send());

  print("Result: ${response.body}");

  return JSON.decode(response.body);

}
9udxz4iz

9udxz4iz1#

你可以尝试添加headers,如下所示

Map<String, String> headers = { "Accesstoken": "access_token"};

final multipartRequest = new http.MultipartRequest('POST', Uri.parse(apiUrl))
multipartRequest.headers.addAll(headers);
multipartRequest.files.add(..)
lc8prwob

lc8prwob2#

var request = http.MultipartRequest(
    "POST",
    Uri.parse(
      "${Urls().url}/support/tenant/register",
    ),
  );
  //add text fields
  
  request.headers["authorization"]=userToken;

  request.fields["type"] = type;
  request.fields["note"] = note;
  for (var item in path) {
    var ext = item.split('.').last;
    var pic = await http.MultipartFile.fromPath("images", item, contentType: MediaType('image', ext));
    request.files.add(pic);
  }

  //add multipart to request

  var response = await request.send();
  var responseData = await response.stream.toBytes();
  var responseString = String.fromCharCodes(responseData);

  var d = jsonDecode(responseString);
093gszye

093gszye3#

分享完整的代码,以供参考如何在头中添加授权:

String url = "https://api.com";

    var request = new http.MultipartRequest("POST", Uri.parse(url));
    request.headers['Authorization'] =
    'Bearer xxxxxxxxxxxxxxxxx';
    request.headers['x-app-key'] = '943691';
    request.fields['category'] =
    '<letter>h</letter><letter>o</letter><letter>m</letter><letter>e</letter>';
    request.fields['categoryA'] = '<letter>a</letter>';
    
    request.files.add(await http.MultipartFile.fromPath(
      'file',
      '/data/user/0/com/cache/abc.wav',
      contentType: MediaType('application', 'audio/wav'),
    ));

    try {
    var response = await request.send();
    var res = await http.Response.fromStream(response);

    if (res.statusCode == 200)
      print("SUCCESS! 200 HTTP");

      print("HTTP CODE:${res.statusCode}");
      String respString = res.body;
      print("respString::$respString");
    SpellRoot spellRoot=spellRootFromJson(respString);
    return spellRoot;
    } catch (e, s) {
      print("ERRR 200 responsecode");
      print("$e __ $s");
    
  }

相关问题