简体   繁体   中英

how to upload images in flutter

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...:(

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();
}

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');
  }

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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM