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

后端 未结 11 1054
攒了一身酷
攒了一身酷 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 22:56

    I found a working example without using any external plugin , this only uses

    import 'package:http/http.dart' as http;
    import 'dart:io';
    import 'package:path/path.dart';
    import 'package:async/async.dart';
    import 'dart:convert';
    

    Code

    var stream =
            new http.ByteStream(DelegatingStream.typed(imageFile.openRead()));
        // get file length
        var length = await imageFile.length(); //imageFile is your image file
        Map 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);
    
        });
    

提交回复
热议问题