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

后端 未结 11 914
攒了一身酷
攒了一身酷 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<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);
    
        });
    
    0 讨论(0)
  • 2020-11-29 22:57

    Use MultipartRequest class. How to upload image file using restAPI in flutter/dart

      void uploadImage1(File _image) async {
    
        // open a byteStream
        var stream = new http.ByteStream(DelegatingStream.typed(_image.openRead()));
        // get file length
        var length = await _image.length();
    
        // string to uri
        var uri = Uri.parse("enter here upload URL");
    
        // create multipart request
        var request = new http.MultipartRequest("POST", uri);
    
        // if you need more parameters to parse, add those like this. i added "user_id". here this "user_id" is a key of the API request
        request.fields["user_id"] = "text";
    
        // multipart that takes file.. here this "image_file" is a key of the API request
        var multipartFile = new http.MultipartFile('image_file', stream, length, filename: basename(_image.path));
    
        // add file to multipart
        request.files.add(multipartFile);
    
        // send request to upload image
        await request.send().then((response) async {
          // listen for response
          response.stream.transform(utf8.decoder).listen((value) {
            print(value);
          });
    
        }).catchError((e) {
          print(e);
        });
      }
    

    name spaces:

    import 'package:path/path.dart';
    import 'package:async/async.dart';
    import 'dart:io';
    import 'package:http/http.dart' as http;
    
    0 讨论(0)
  • 2020-11-29 23:00

    Your workaround should work; many servers will accept application/x-www-form-urlencoded as an alternative (although data is encoded moderately inefficiently).

    However, it is possible to use dart:http to do this. Instead of using http.post, you'll want to use a http.MultipartFile object.

    From the dart documentation:

    var request = new http.MultipartRequest("POST", url);
    request.fields['user'] = 'someone@somewhere.com';
    request.files.add(http.MultipartFile.fromPath(
        'package',
        'build/package.tar.gz',
        contentType: new MediaType('application', 'x-tar'),
    ));
    request.send().then((response) {
      if (response.statusCode == 200) print("Uploaded!");
    });
    
    0 讨论(0)
  • 2020-11-29 23:02

    I'd like to recommend dio package to you , dio is a powerful Http client for Dart/Flutter, which supports Interceptors, FormData, Request Cancellation, File Downloading, Timeout etc.

    dio is very easy to use, in this case you can:

    Sending FormData:

    FormData formData = new FormData.from({
       "name": "wendux",
       "file1": new UploadFileInfo(new File("./upload.jpg"), "upload1.jpg")
    });
    response = await dio.post("/info", data: formData)
    

    More details please refer to dio。

    0 讨论(0)
  • 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 = '<YOUR-URL>';
    
          //[2] ADDING TOKEN
          dioRequest.options.headers = {
            'Authorization': '<IF-YOU-NEED-ADD-TOKEN-HERE>',
            'Content-Type': 'application/x-www-form-urlencoded'
          };
    
          //[3] ADDING EXTRA INFO
          var formData =
              new dio.FormData.fromMap({'<SOME-EXTRA-FIELD>': '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');
        }
    
    0 讨论(0)
提交回复
热议问题