2

I am trying to send image from flutter to django-rest-framework using following code but the image is not uploaded for some reason. I can't figure out the problem. I have used MultiPart library for the image upload. I tried debugging the code and the code gets stuck on var response and the print statement "code" is not displayed on the console.

This is code I wrote in flutter:

File _image;
  String message = '';
  String url =
      'http://IP_address:8000/upload/'; 
  bool loading = false;
  pickImage() async {
    File image = await ImagePicker.pickImage(source: ImageSource.gallery);

    setState(() => _image = image);
  }

  upload(File file) async {
    if (file == null) return;

    setState(() {
      loading = true;
    
    });
    Map<String, String> headers = {
      "Content-Type": "application/json",
    };
    var uri = Uri.parse(url);
    var length = await file.length();
    print(length);
    http.MultipartRequest request = new http.MultipartRequest('POST', uri)
      ..headers.addAll(headers)
      ..files.add(
        http.MultipartFile('img', file.openRead(), length,
            filename: 'test.png'),
      );
      print("done");
    var respons = await http.Response.fromStream(await request.send());
    print("code");
    print(respons.statusCode);
    setState(() {
      loading = false;
    });
    if (respons.statusCode == 201) {
      setState(() {
        message = ' image upload with success';
      });
      return;
    } else
      setState(() {
        message = ' image not upload';
      });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          loading
              ? Padding(
                  padding: EdgeInsets.only(top: 52),
                  child: Center(child: CircularProgressIndicator()),
                )
              : _image != null
                  ? Image.file(
                      _image,
                      height: MediaQuery.of(context).size.height * 0.4,
                      width: double.infinity,
                      fit: BoxFit.cover,
                    )
                  : Image.network(
                      'https://www.generationsforpeace.org/wp-content/uploads/2018/03/empty.jpg'),
          Text(message),
          Row(
            children: <Widget>[
              Expanded(
                child: RaisedButton(
                  onPressed: () => pickImage(),
                  child: Text('Pick Image'),
                ),
              ),
              Expanded(
                child: RaisedButton(
                  onPressed: () => upload(_image),
                  child: Text('upload image'),
                ),
              ),
            ],
          )
        ],
      ),
    );

}

This is code in Django: models.py

class Food(models.Model):
    img = models.ImageField(upload_to = "images/")

urls.py

router = routers.DefaultRouter()
router.register(r'upload', views.PhotoViewSet)

urlpatterns = [
    path('', include(router.urls)),
    path('api-auth/', include('rest_framework.urls', namespace='rest_framework')),
Mrunal Joshi
  • 367
  • 1
  • 4
  • 11
  • Please check this answer on [stackoverflow](https://stackoverflow.com/questions/67667243/how-to-upload-images-in-flutter/72448103#72448103:~:text=to%20upload%20your%20image) – victor-dickson May 31 '22 at 13:01

0 Answers0