简体   繁体   中英

How to Pick files and Images for upload with flutter web

I would like to know how to pick an Image from the users computer into my flutter web app for upload

I tried the code below and it worked.

first import 'dart:html';

// variable to hold image to be displayed 

      Uint8List uploadedImage;

//method to load image and update `uploadedImage`


    _startFilePicker() async {
    InputElement uploadInput = FileUploadInputElement();
    uploadInput.click();

    uploadInput.onChange.listen((e) {
      // read file content as dataURL
      final files = uploadInput.files;
      if (files.length == 1) {
        final file = files[0];
        FileReader reader =  FileReader();

        reader.onLoadEnd.listen((e) {
                    setState(() {
                      uploadedImage = reader.result;
                    });
        });

        reader.onError.listen((fileEvent) {
          setState(() {
            option1Text = "Some Error occured while reading the file";
          });
        });

        reader.readAsArrayBuffer(file);
      }
    });
    }

now just any Widget, like a button and call the method _startFilePicker()

The accepted answer is outdated, and using dart:html package directly in Flutter is not recommended.

Instead, use this package: https://pub.dev/packages/file_picker .

Example of how to use in Flutter Web:

class FileUploadButton extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return RaisedButton(
      child: Text('UPLOAD FILE'),
      onPressed: () async {
        var picked = await FilePicker.platform.pickFiles();

        if (picked != null) {
          print(picked.files.first.name);
        }
      },
    );
  }
}

Note that FilePickerResult.path is not supported in Flutter Web.

import 'package:http/http.dart' as http;
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';

class FileUploadWithHttp extends StatefulWidget {
  @override
  _FileUploadWithHttpState createState() => _FileUploadWithHttpState();
}

class _FileUploadWithHttpState extends State<FileUploadWithHttp> {
  PlatformFile objFile = null;

  void chooseFileUsingFilePicker() async {
    //-----pick file by file picker,

    var result = await FilePicker.platform.pickFiles(
      withReadStream:
          true, // this will return PlatformFile object with read stream
    );
    if (result != null) {
      setState(() {
        objFile = result.files.single;
      });
    }
  }

  void uploadSelectedFile() async {
    //---Create http package multipart request object
    final request = http.MultipartRequest(
      "POST",
      Uri.parse("Your API URL"),
    );
    //-----add other fields if needed
    request.fields["id"] = "abc";

    //-----add selected file with request
    request.files.add(new http.MultipartFile(
        "Your parameter name on server side", objFile.readStream, objFile.size,
        filename: objFile.name));

    //-------Send request
    var resp = await request.send();

    //------Read response
    String result = await resp.stream.bytesToString();

    //-------Your response
    print(result);
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(
        children: [
          //------Button to choose file using file picker plugin
          RaisedButton(
              child: Text("Choose File"),
              onPressed: () => chooseFileUsingFilePicker()),
          //------Show file name when file is selected
          if (objFile != null) Text("File name : ${objFile.name}"),
          //------Show file size when file is selected
          if (objFile != null) Text("File size : ${objFile.size} bytes"),
          //------Show upload utton when file is selected
          RaisedButton(
              child: Text("Upload"), onPressed: () => uploadSelectedFile()),
        ],
      ),
    );
  }
}

I've tested this package and was very happy with the result imagePickerWeb it returns 3 different types it can be in the form of Image(widget for preview), byte, File(upload)

then you can use this to get the values

html.File _cloudFile;
 var _fileBytes;
 Image _imageWidget;
 
 Future<void> getMultipleImageInfos() async {
    var mediaData = await ImagePickerWeb.getImageInfo;
    String mimeType = mime(Path.basename(mediaData.fileName));
    html.File mediaFile =
        new html.File(mediaData.data, mediaData.fileName, {'type': mimeType});

    if (mediaFile != null) {
      setState(() {
        _cloudFile = mediaFile;
        _fileBytes = mediaData.data;
        _imageWidget = Image.memory(mediaData.data);
      });
    }

Uploading to firebase

don't forget to add this to your index.html

  <script src="https://www.gstatic.com/firebasejs/7.5.0/firebase-storage.js"></script>

Uploading to firebase

import 'package:firebase/firebase.dart' as fb;
    uploadToFirebase(File file) async {

    final filePath = 'temp/${DateTime.now()}.png';//path to save Storage
    try {
      fb
          .storage()
          .refFromURL('urlFromStorage')
          .child(filePath)
          .put(file);
    } catch (e) {
      print('error:$e');
    }
  }

See the documentation of the package if you still have problems

The accepted answer is indeed outdated. Like jnt suggested, https://pub.dev/packages/file_picker is a handy package, when it comes to implementing an image upload using Flutter Web.

The problem I was facing is to get a base64 representation of an image, since I was using it to store images in Firestore . As we know, dart:io is not supported on Flutter Web and throws Unsupported operation: _Namespace error. Hence, using File and reading file's bytes was not an option. Luckily, the package provides API to convert the uploaded image to Uint8List . Here is my implementation:

import 'package:file_picker/file_picker.dart';

...

FilePickerResult? pickedFile;

...

void chooseImage() async {
    pickedFile = await FilePicker.platform.pickFiles();
    if (pickedFile != null) {
      try {
        setState(() {
          logoBase64 = pickedFile!.files.first.bytes;
        });
      } catch (err) {
        print(err);
      }
    } else {
      print('No Image Selected');
    }
}

In case you need to display the local image right away, use Image.memory .

Image.memory(logoBase64!);

i have this problem too;

i use https://pub.dev/packages/file_picker but in flutter web path not suppor;

you should to use bytes;

i save file bytes in var _fileBytes and use in request;

var request = http.MultipartRequest('POST', Uri.parse('https://.....com'));
request.headers.addAll(headers);
request.files.add(
   http.MultipartFile.fromBytes(
     'image', 
      await ConvertFileToCast(_fileBytes),
      filename: fileName,
      contentType: MediaType('*', '*')
   )
);
request.fields.addAll(fields);
var response = await request.send();

function ConvertFileToCast:

ConvertFileToCast(data){
  List<int> list = data.cast();
  return list;
}

it`s work for me :)

if anyone is wondering how to get it working on mobile and web:

var bytes;
      await file!.files.first.readStream!
          .map((asciiValue) => bytes = asciiValue)
          .toList();
      
 FormData body;
 final MultipartFile file = MultipartFile.fromBytes(bytes, filename: "file");
 MapEntry<String, MultipartFile> imageEntry = MapEntry("image", file);
 body.files.add(imageEntry);

I can share the way I upload image to AWS s3 from flutter web recently. May not exact match the case who is looking for answer here but I think it may inpired others somehow.

First I try to use amplify_storage_s3 package but it not support for Flutter Web yet for now. So I use basic http post instead.

The packages I use:

  • file_picker : For web, FileUploadInputElement (from html package) may do the same thing but I think using this package can make thing simpler.
  • dio : I'm not sure why I cannot use http 's MultipartFile successfully so I use this instead. (maybe someone can provide a version using http package)
  • mine : transfer extension to mimetype

Code example:

import 'package:flutter/material.dart';
import 'package:dio/dio.dart' as dio;
import 'package:file_picker/file_picker.dart';
import 'package:mime/mime.dart';

class FileUploader extends StatelessWidget {
  const FileUploader({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      floatingActionButton: FloatingActionButton(
        onPressed: () async {
          // 1. Pick an image file
          final filePicked = await FilePicker.platform.pickFiles();
          if (filePicked != null) {
            final file = filePicked.files.single; // PlatformFile
            final mimeType = lookupMimeType(file.name) ?? '';

            /// 2. Get presigned data somewhere
            const url = 'https://s3.amazonaws.com/......';
            final fields = {
              'bucket': '...',
              'X-Amz-Algorithm': 'AWS4-HMAC-SHA256',
              'X-Amz-Credential': '...',
              'X-Amz-Date': '...',
              'Policy': '...',
              'X-Amz-Signature': '...',
              'x-amz-meta-userid': '...',
              'Content-Type': mimeType,
              'file': dio.MultipartFile.fromBytes(file.bytes ?? []),
            };

            /// 3. Send file to AWS s3
            final formData = dio.FormData.fromMap(fields);
            await dio.Dio().post(url, data: formData);
          }
        },
        child: const Icon(Icons.upload),
      ),
    );
  }
}

Here is my working code to upload using dio. I use dio because it has a callback progress function.

class _FileUploadViewState extends State<FileUploadView> {
  @override
  void initState() {
    super.initState();
  }

  FilePickerResult? result;
  PlatformFile? file;
  Response? response;
  String? progress;
  String? percentage;
  Dio dio = Dio();

  selectFile() async {
    result =
        await FilePicker.platform.pickFiles(type: FileType.any, withData: true);

    if (result != null) {
      file = result?.files.single;
    }

    //print(file?.name);
    //print(file?.bytes?.length);
    //print(file?.size);
    //print(file?.extension);
    //print(file?.path);

    setState(() {});
  }

  Future<void> uploadFile(BuildContext context, User user) async {
    final navigator = Navigator.of(context);

    final storage = FlutterSecureStorage();

    String? token = await storage.read(key: 'jwt');

    final formData = FormData.fromMap(
      {
        'file': MultipartFile.fromBytes(file?.bytes as List<int>,
            filename: file?.name)
      },
    );

    dio.options.headers['content-Type'] = 'application/octet-stream';
    dio.options.headers["authorization"] = "Bearer $token";

    response = await dio.post(
      user.fileUrl,
      data: formData,
      onSendProgress: (int sent, int total) {
        percentage = (sent / total * 100).toStringAsFixed(2);
        progress = "$sent Bytes of $total Bytes - $percentage % uploaded";
        setState(
          () {},
        );
      },
    );

    if (response!.statusCode == 200) {
    ....

My go code for the server looks like this,

if err := r.ParseMultipartForm(64 << 20); err != nil {
    log.Println("error processing multipart form")
    log.Println(err)
    http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
    return
}

file, handler, err := r.FormFile("file")

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