如何挑选文件和图像以通过Flutter Web上传

Nor*_*ert 5 dart flutter flutter-web

我想知道如何将用户计算机中的图像选入我的Flutter Web应用程序中进行上传

Nor*_*ert 31

我尝试了下面的代码,它奏效了。

第一的 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);
      }
    });
    }
Run Code Online (Sandbox Code Playgroud)

现在只是任何小部件,如按钮并调用该方法 _startFilePicker()


jnt*_*jnt 17

接受的答案已经过时,dart:html不建议直接在 Flutter 中使用package。

相反,使用这个包:https : //pub.dev/packages/file_picker

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);
        }
      },
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

请注意,FilePickerResult.pathFlutter Web 不支持它。

  • 这在 flutter web 中有效,但不需要路径,也没有实现,如文档中[明确](https://github.com/miguelpruivo/flutter_file_picker/wiki/API#-getdirectorypath)所述。只需使用“PlatformFile.bytes”属性即可访问字节。 (3认同)
  • 我正在使用此依赖项,但没有获取路径。我必须将其上传到 firebase 。那么 flutter web 使用什么来选择 web 的文件路径 (2认同)
  • 为什么我总是在 .bytes 上得到 null ? (2认同)

Lad*_*hbu 7

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()),
        ],
      ),
    );
  }
}
Run Code Online (Sandbox Code Playgroud)


Dea*_*mia 6

我已经测试了这个包并且对结果非常满意imagePickerWeb它返回 3 种不同的类型 它可以是图像(预览小部件)、字节、文件(上传)的形式

然后您可以使用它来获取值

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);
      });
    }
Run Code Online (Sandbox Code Playgroud)

上传到火力基地

不要忘记将此添加到您的 index.html

  <script src="https://www.gstatic.com/firebasejs/7.5.0/firebase-storage.js"></script>
Run Code Online (Sandbox Code Playgroud)

上传到火力基地

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');
    }
  }
Run Code Online (Sandbox Code Playgroud)

如果仍有问题,请参阅软件包的文档