How to upload images and file to a server in Flutter?

后端 未结 11 1029
攒了一身酷
攒了一身酷 2020-11-29 22:21

I use a web service for image processing , it works well in Postman:

Now I want to make http request in flutter with Dart:

import \'pa         


        
11条回答
  •  一生所求
    2020-11-29 23:03

    UPLOAD IMAGE TO SERVER WITH FORM DATA

    To upload image to server you need a dio library.

    Features:

    1. Authorization (adding token)
    2. Adding extra field like: username, etc
    3. Adding Image to upload

    Code example:

    import 'package:dio/dio.dart' as dio;
    import 'dart:convert';
    
        try {
          ///[1] CREATING INSTANCE
          var dioRequest = dio.Dio();
          dioRequest.options.baseUrl = '';
    
          //[2] ADDING TOKEN
          dioRequest.options.headers = {
            'Authorization': '',
            'Content-Type': 'application/x-www-form-urlencoded'
          };
    
          //[3] ADDING EXTRA INFO
          var formData =
              new dio.FormData.fromMap({'': 'username-forexample'});
    
          //[4] ADD IMAGE TO UPLOAD
          var file = await dio.MultipartFile.fromFile(image.path,
                filename: basename(image.path),
                contentType: MediaType("image", basename(image.path)));
    
          formData.files.add(MapEntry('photo', file));
    
          //[5] SEND TO SERVER
          var response = await dioRequest.post(
            url,
            data: formData,
          );
          final result = json.decode(response.toString())['result'];
        } catch (err) {
          print('ERROR  $err');
        }
    

提交回复
热议问题