如何在Flutter中上传图片?

kar*_* vs 8 dart flutter

我想上传一张图片,我正在使用http.Client()来发送请求,

static uploadImage(String id, File file) {
  var httpClient = createHttpClient();

  Map<String, String> headers = new Map<String, String>();
  headers.putIfAbsent("Authorization", () => "---");
  headers.putIfAbsent("Content-Type", () => "application/json");

  var body=new List();
  body.add(id.)
  httpClient.post(URL_UPLOADIMAGE,headers: headers,body: ,encoding: )
}
Run Code Online (Sandbox Code Playgroud)

请求的正文和编码部分应该是什么?

Shy*_*hil 24

使用MultipartRequest

Upload(File imageFile) async {    
    var stream = new http.ByteStream(DelegatingStream.typed(imageFile.openRead()));
      var length = await imageFile.length();

      var uri = Uri.parse(uploadURL);

     var request = new http.MultipartRequest("POST", uri);
      var multipartFile = new http.MultipartFile('file', stream, length,
          filename: basename(imageFile.path));
          //contentType: new MediaType('image', 'png'));

      request.files.add(multipartFile);
      var response = await request.send();
      print(response.statusCode);
      response.stream.transform(utf8.decoder).listen((value) {
        print(value);
      });
    }
Run Code Online (Sandbox Code Playgroud)

名称空间:

import 'package:path/path.dart';
import 'package:async/async.dart';
import 'dart:io';
import 'package:http/http.dart' as http;
Run Code Online (Sandbox Code Playgroud)

  • DelegatingStream.typed 已弃用。 (4认同)
  • 我上传的文件始终是“application/octet-stream”。有没有办法从文件中获取正确的内容类型以及如何在请求中设置它? (3认同)
  • 我想我只需要 `import 'package:http_parser/http_parser.dart';` (3认同)
  • 我从哪里导入 MediaType 类 (2认同)
  • 使用 `var Stream = new http.ByteStream(_image.openRead()); Stream.cast();` 代替 `DelegatingStream.typed` (2认同)

Raj*_*dav 23

最简单的方法是使用http库,

import 'dart:io';
import 'package:http/http.dart' as http;

_asyncFileUpload(String text, File file) async{
   //create multipart request for POST or PATCH method
   var request = http.MultipartRequest("POST", Uri.parse("<url>"));
   //add text fields
   request.fields["text_field"] = text;
   //create multipart using filepath, string or bytes
   var pic = await http.MultipartFile.fromPath("file_field", file.path);
   //add multipart to request
   request.files.add(pic);
   var response = await request.send();

   //Get the response from the server
   var responseData = await response.stream.toBytes();
   var responseString = String.fromCharCodes(responseData);
   print(responseString);
}
Run Code Online (Sandbox Code Playgroud)

  • 您好,它给了我未处理的异常:SocketException:操作系统错误:损坏的管道,errno = 32,请提出建议 (2认同)

Ara*_*ula 7

submitForm()方法中检出主体。

File _image;

Future cameraImage() async {
  var image = await ImagePicker.pickImage(
    source: ImageSource.camera,
    maxHeight: 240.0,
    maxWidth: 240.0,
  );

  setState(() {
    _image = image;
  });
}

submitForm() async {
  final response = await http.post(
    uri,
    headers: {
      AuthUtils.AUTH_HEADER: _authToken
    },
    body: {
      'user_id': userId
      'photo': _image != null ? 'data:image/png;base64,' +
          base64Encode(_image.readAsBytesSync()) : '',
    },
  );

  final responseJson = json.decode(response.body);

  print(responseJson);
}
Run Code Online (Sandbox Code Playgroud)


Qui*_*ner 7

我找到了一个不使用任何外部插件的工作示例,这只使用

import 'package:http/http.dart' as http;
Run Code Online (Sandbox Code Playgroud)

代码

var stream =
        new http.ByteStream(DelegatingStream.typed(imageFile.openRead()));
    // get file length
    var length = await imageFile.length(); //imageFile is your image file
    Map<String, String> headers = {
      "Accept": "application/json",
      "Authorization": "Bearer " + token
    }; // ignore this headers if there is no authentication

    // string to uri
    var uri = Uri.parse(Constants.BASE_URL + "api endpoint here");

    // create multipart request
    var request = new http.MultipartRequest("POST", uri);

  // multipart that takes file
    var multipartFileSign = new http.MultipartFile('profile_pic', stream, length,
        filename: basename(imageFile.path));

    // add file to multipart
    request.files.add(multipartFileSign);

    //add headers
    request.headers.addAll(headers);

    //adding params
    request.fields['loginId'] = '12';
    request.fields['firstName'] = 'abc';
   // request.fields['lastName'] = 'efg';

    // send
    var response = await request.send();

    print(response.statusCode);

    // listen for response
    response.stream.transform(utf8.decoder).listen((value) {
      print(value);

    });
Run Code Online (Sandbox Code Playgroud)

  • 当我使用你的代码时,它给我错误说“图像”:[“没有提交文件。”]`。关于如何解决这个问题有什么想法吗? (2认同)

Tej*_*oid 6

我已经尝试了所有但没有以上工作的服务器上传文件。

经过深入搜索,我得到了与Dio相同的插件。

以下代码用于服务器中的上传文件

uploadFileFromDio(UserProfile userProfile, File photoFile) async {
    var dio = new Dio();
    dio.options.baseUrl = url;
    dio.options.connectTimeout = 5000; //5s
    dio.options.receiveTimeout = 5000;
    dio.options.headers = <Header Json>;
    FormData formData = new FormData();
    formData.add("user_id", userProfile.userId);
    formData.add("name", userProfile.name);
    formData.add("email", userProfile.email);

    if (photoFile != null &&
        photoFile.path != null &&
        photoFile.path.isNotEmpty) {
      // Create a FormData
      String fileName = basename(photoFile.path);
      print("File Name : $fileName");
      print("File Size : ${photoFile.lengthSync()}");
      formData.add("user_picture", new UploadFileInfo(photoFile, fileName));
    }
    var response = await dio.post("user/manage_profile",
        data: formData,
        options: Options(
            method: 'POST',
            responseType: ResponseType.PLAIN // or ResponseType.JSON
            ));
    print("Response status: ${response.statusCode}");
    print("Response data: ${response.data}");
  }
Run Code Online (Sandbox Code Playgroud)


Bob*_*ban 6

请尝试以下解决方案

Future<String> uploadImageHTTP(file, url) async {

  var request = http.MultipartRequest('POST', Uri.parse(url));
  request.files.add(await http.MultipartFile.fromPath('picture', file.path));
  var res = await request.send();
  return res.reasonPhrase;

}
Run Code Online (Sandbox Code Playgroud)


Col*_*son 5

考虑使用 Flutter 的Firebase Storage 插件——它具有在移动连接上上传大型图像文件可能有用的功能。

我写了插件,欢迎贡献和反馈!

  • “使用 Firebase 插件(我编写的)”并不是“如何在 Flutter 中上传图像?”的答案。 (2认同)