0

hello i wonder to upload images in flutter

i try to use http.MultipartRequest like this

  request.fields["name"] = "$RegisterName";
  request.fields["description"] = "$RegisterDescription";
  request.fields["caution"] = "$RegisterCaution";
  request.fields["price"] = "$RegisterPrice";
  request.fields["price_prop"] = "$RegisterPriceProp";
  request.fields["user.id"] = "1";
  request.fields["lend"] = "$RegisterCategory";
  request.fields["category"] = "Digital";
  request.fields["place_option"] = "true";

  var multipartFile = http.MultipartFile.fromBytes(
    'file',
    (await rootBundle.load('assets/images/main_1.jpg')).buffer.asUint8List(),
    filename: 'test01.jpg',
    contentType: MediaType('image', 'jpg'),
  );

  request.files.add(multipartFile);
  

  var response = await request.send();

  if (response.statusCode == 200) print('Upload');
}

but this code is not working if i use this code, upload only another data upload things

then json type is this json type image

i want upload images files ...:(

Lily
  • 21
  • 4

3 Answers3

0

i use this to send picture with formData

var head = Api().bearerHeader; ////just bearerToken
var request = http.MultipartRequest(
    'POST',
    Uri.parse(
        'https://c.....'));
request.files
    .add(await http.MultipartFile.fromPath('TITLEOFFORMDATA', imageFile.path));
request.headers.addAll(head);

http.StreamedResponse response = await request.send();

if (response.statusCode == 200) {
  String varo = await response.stream.bytesToString();
}
Ardeshir ojan
  • 1,914
  • 1
  • 13
  • 36
0

This is how you can send image to your server with MultipartRequest with http package

 try {
    final uri = Uri.parse(your_url);

    final request = http.MultipartRequest('POST', uri);

    final multipartFile =
        await http.MultipartFile.fromPath('Image', 'your_path_of_image'); // Image is the parameter name 

    request.files.add(multipartFile);

    request.fields['userId_if_required'] = value;

    final response = await request.send();
    if (response.statusCode == 200) {
      print('success');
    } else {
      print('Something went wrong');
    }
  } catch (e) {
    print('Something went wrong');
  }
Hemal Moradiya
  • 1,715
  • 1
  • 6
  • 26
  • thank you.. but i have another problem.... :( (OS Error: No such file or directory, errno = 2) what can i do..? actually i cant understand upload system.... – Lily May 25 '21 at 05:01
  • @Lily You've to convert your asset image to `File` formate please refer this link https://stackoverflow.com/questions/55295593/how-to-convert-asset-image-to-file – Hemal Moradiya May 25 '21 at 05:31
0

How to upload your image to a Django rest API server this will work for sure, let me know if you have any issues. Please be sure to add the necessary packages to your pubspec.yaml file

image_picker http

if there is some I missed please ask me or add it and add as a reply

import 'dart:convert';
import 'package:http/http.dart' as http;
import 'dart:io';
import 'package:get/get.dart';
import 'package:image_picker/image_picker.dart';

final _picker = ImagePicker();
File? _image;

// use this to send your image
Future<void>uploadImage(filePath) async {
    // your token if needed
    try{
    var headers = {
        'Authorization':
                'Bearer ' + "token",
    };
    // your endpoint and request method
    var request = http.MultipartRequest(
        'POST',
        Uri.parse("https://api.imgur.com/3/image"));

    request.fields
            .addAll({'yourFieldNameKey1': 'yourFieldNameValue1', 'yourFieldNameKey2': 'yourFieldNameValue2'});
        request.files.add(await http.MultipartFile.fromPath(
            'yourPictureKey', filePath));
    request.headers.addAll(headers);

    http.StreamedResponse response = await request.send();

    if (response.statusCode == 200) {
        print(await response.stream.bytesToString());
    } else {
        print(response.reasonPhrase);
    }
    }catch(e){
        print(e);
    }
}

// Use this to pick your image

Future<void> _openImagePicker() async {
    try {
        var pickedImage = await _picker.pickImage(source: ImageSource.gallery);
        if (pickedImage != null) {
            setState(() {
                _image = File(pickedImage.path);
            });
            uploadImage(pickedImage.path);
        }
    } catch (e) {
      //print(e);
    }
}
  • hey, Im having trouble with this in Flutter WEB. in normal ios/android flutter, the mulitpart.FROMPATH works but for somereason it doens't work with flutter web since you cant use dart/io with browsers. I tried the multipart.FROMBYTES instead but im still not sure how to handle it in the back end (Django REST API). any help would be appreciated thanks – Karan V Dec 02 '22 at 02:51