dart 我无法上传一个图像到后端使用http和图像选择器为flutter网络

webghufk  于 12个月前  发布在  Flutter
关注(0)|答案(4)|浏览(104)
  • 这里是我使用http上传到服务器的函数。我尝试将图像转换为base64字符串,但问题仍然存在 *
uploadImage() async {

var postUri = Uri.parse('${xyz}/api/v1/listing/store');
var request = new http.MultipartRequest("POST", postUri);
request.fields['name'] = titleTEC.text.toString();
request.fields['category_id'] = selectedCategoryId.toString();
request.fields['price'] = priceTEC.text.toString();
request.fields['discount'] = 2.toString();
request.fields['discount_type'] = 'percent';
request.headers['moduleId'] = 2.toString();
Uint8List _list = await singleImage.readAsBytes();
request.files.add(http.MultipartFile(
  'image', singleImage.readAsBytes().asStream(), _list.length,
  filename: '${DateTime.now().toString()}.png',
));

// request.files.add(new http.MultipartFile.fromString('image', base64Image));

request.send().then((response) {

  print(response.statusCode);
});

}

mznpcxlj

mznpcxlj1#

你可以使用这个代码,它的工作完美

Future<String> uploadImage(String username,String password,File? image,String desc) async {

Map<String,String> body = {
  "username"          : username,
  "password"          : password,
  "desc"              : desc,
};

var response = http.MultipartRequest(
  "POST",
  Uri.parse("$dataURL/prescription"),
);
final httpImage = http.MultipartFile("image" , image!.readAsBytes().asStream(),image.lengthSync(),filename: image.path);

response.headers.addAll({'Content-type' : 'application/json' , 'Accept' : 'application/json'});
response.fields.addAll(body);
response.files.add(httpImage);

http.StreamResponse result = await response.send();

print("checkedUpload: ${result.statusCode}");

return await result.stream.bytesToString();

}

hmae6n7t

hmae6n7t2#

查看堆栈跟踪,似乎您正在调用dart:io代码,这在Web上不受支持。您确定sixam_mart代码设计为在浏览器中工作吗?

z4iuyo4d

z4iuyo4d3#

使用dio包,它也用于API调用,它的效果很好。

Future updateProfilePicApi(File profilepic) async {
    dynamic responseJson;
    try {
      var dio = Dio();
     
      String fileName = profilepic.path.split('/').last;
      FormData formData = FormData.fromMap({
        
        "image":
            await MultipartFile.fromFile(profilepic.path, filename: fileName),
      });

      var response = await dio.post('${xyz}/api/v1/listing/store',
          options: Options(
              headers: {
                'Accept': 'application/json',
                
              },
              followRedirects: false,
              validateStatus: (status) {
                return status! <= 500;
              }),
          data: formData);
      print("::::::::::::::::status code::::::::::::::");
      print(response.statusCode);
      responseJson = response.data;
    } on SocketException {
      print("no internet");
    }
    return responseJson;
  }
e37o9pze

e37o9pze4#

使用路径添加图像文件
request.files.add(await http.MultipartFile.fromPath('image',filepath));

相关问题