Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can not specify the content type of MultiPartFile in Flutter

I'm trying to send an image to a server via multiPartRequest in flutter and when I add the image into the request files, once I want to specify the content type which is of MediaType, a compile-time error appear telling me that MediaType class is not defined.

How can I fix this problem?

http.MultipartRequest multipartRequest = new http.MultipartRequest('POST',url);
http.MultipartFile file = new http.MultipartFile.fromBytes('file', await 
image.readAsBytes(),contentType: MediaType('image','jpg));  // MediaType class is not defined
multipartRequest.files.add(file);
like image 262
Karrar Avatar asked Jan 24 '20 14:01

Karrar


3 Answers

you need to import:

 import 'package:http_parser/http_parser.dart';
like image 66
Mina Farid Avatar answered Nov 10 '22 12:11

Mina Farid


Just check out this if it works

uploadFile() async {
    var postUri = Uri.parse("<APIUrl>");
    var request = new http.MultipartRequest("POST", postUri);
    request.fields['user'] = 'blah';
    request.files.add(new http.MultipartFile.fromBytes('file', await File.fromUri("<path/to/file").readAsBytes(), contentType: new MediaType('image', 'jpeg')))

    request.send().then((response) {
      if (response.statusCode == 200) print("Uploaded!");
    });
  }
like image 8
Sagar Acharya Avatar answered Nov 10 '22 14:11

Sagar Acharya


I figured out the answer and it is that I must import http parser package

like image 8
Karrar Avatar answered Nov 10 '22 13:11

Karrar