【问题标题】:How to convert Uint8List image to File Image for upload in flutter web如何将 Uint8List 图像转换为文件图像以在 Flutter Web 中上传
【发布时间】:2020-03-06 16:56:12
【问题描述】:

我已经能够从我的计算机中选择一个文件并显示在我的 Flutter Web 应用程序中。 我有一个函数(类型为File),它获取一个文件并将其上传到服务器。像这样functionName(File imageToSend)

但是当我尝试将此图像发送到服务器端时,它给了我一个错误。我正在使用以下代码进行上传:

Uint8List uploadedImage;
File theChosenImg;
FileReader reader =  FileReader();
FileReader reader2 = FileReader();

filePicker() 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];    

    reader.onLoadEnd.listen((e) {
                setState(() {
                  uploadedImage = reader.result;
                  theChosenImg = files[0];
                });
    });
    reader.readAsArrayBuffer(file);
    reader2.readAsDataUrl(file);
  }
});
}

当我使用变量uploadedImage 时,错误是Expected a value of type 'File', but got one of type 'String' 然后我决定使用theChosenImg = files[0]; 中的theChosenImg,这也告诉我数据类型不匹配。

我是否可以将Uint8List 数据类型转换为File

使用代码更新

import 'dart:typed_data';
import 'dart:html';
import 'dart:ui' as ui;
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:web_image_upload/impUp.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

class FrontUi extends StatefulWidget {
  @override
  _FrontUiState createState() => _FrontUiState();
}

class _FrontUiState extends State<FrontUi> {

Uint8List uploadedImage;
File theChosenImg;
String dispText = 'Uploaded image should shwo here.';
FileReader reader2 = FileReader();

_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;
                  theChosenImg = files[0];
                });
    });
    reader.readAsArrayBuffer(file);
    reader2.readAsDataUrl(file);
  }
});
}

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: ListView(
          children: <Widget>[
            Column(
              children: <Widget>[
                SizedBox(
                  height: 30,
                ),
                Container(
                  height: 500,
                  width: 800,
                  child: Center(
                    child: uploadedImage == null
                ? Container(
                    child: Text(dispText),
                  )
                : Container(
                    child: Image.memory(uploadedImage),
                  ),
                  ),
                ),
            SizedBox(height: 20,),                
                CupertinoButton(
                  color: Colors.green,
                  child: Text("Choose"),
                  onPressed: (){
                    _startFilePicker();
                  },
                ),

            SizedBox(height: 50,),
             CupertinoButton(
              color: Colors.green,
              child: Text("Upload"),
              onPressed: (){
                PhotoCls().upload(reader2.result);
              },
            ),



              ],
            ),



          ],
        ),
      ),

    );
  }
}

使用发送图像的方法的类

import 'dart:io';
import 'package:path/path.dart';
import 'package:async/async.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';



  class PhotoCls {
 String phpEndPoint = "http://IPv4 address/testlocalhost/uploadPicture.php";


upload(File imageFile) async {    
      // open a bytestream
      var stream = new http.ByteStream(DelegatingStream.typed(imageFile.openRead()));
      // get file length
      var length = await imageFile.length();

      // string to uri
      var uri = Uri.parse(phpEndPoint);

      // create multipart request
      var request = new http.MultipartRequest("POST", uri);

      // multipart that takes file
      var multipartFile = new http.MultipartFile('file', stream, length,
          filename: basename(imageFile.path));

      // add file to multipart
      request.files.add(multipartFile);

      // send
      var response = await request.send();
      print(response.statusCode);

      // listen for response
      response.stream.transform(utf8.decoder).listen((value) {
        print(value);
      });
    }



  }

【问题讨论】:

  • 你能发布你的文件上传代码..!连同您的导入语句。
  • @AbhilashChandran 更新了代码
  • 我确信你不能在flutter_web 的上下文中使用dart:io 库。尝试使用来自dart:html 的文件类。 FileUploadInputElement 返回的文件对象是来自dart:html 库的File 类型。

标签: flutter dart flutter-web


【解决方案1】:
File.fromRawPath(Uint8List uint8List);

【讨论】:

  • 网页不支持 dart io
【解决方案2】:

包含这个包https://pub.dev/packages/path_provider

import 'package:path_provider/path_provider.dart';
import 'dart:io';

Uint8List imageInUnit8List = // store unit8List image here ;
final tempDir = await getTemporaryDirectory();
File file = await File('${tempDir.path}/image.png').create();
file.writeAsBytesSync(imageInUnit8List);

// -.-.-.-    Unit8List ->  File      -.-.-.-  

【讨论】:

  • 这是迄今为止最好的答案....另一个低于估计的答案...
【解决方案3】:

我尝试生成一个可以同时支持设备和网络的代码。

因为 File.fromRawPath() 使用 dart:io 并且它不适用于 web。

这是我的解决方案:

Uint8List imageCroppedBytes;

首先,我用image_picker 挑选了我的图像,然后用extended_image 裁剪。

在裁剪后的代码中,我将裁剪后的字节文件编码为 jpg。

imageCroppedBytes = Image.encodeJpg(src , quality: 80);

然后:

var image = http.MultipartFile.fromBytes('image', imageCroppedBytes ,filename: 'profileImage.jpg');
request.files.add(image);
await request.send().then((value) async {
    if(value.statusCode == 200) {
      Do Something ...
    }
});

在我的情况下,我有一个带有 Multer 的 NodeJs 来获取文件并保存它。

已编辑:

import 'package:image/image.dart' as Image;

更多帮助代码:

var data = editorKey.currentState.rawImageData;
Image.Image src = Image.decodeImage(data);
src = Image.copyCrop(src, cropRect.left.toInt(), cropRect.top.toInt(),
                          cropRect.width.toInt(), cropRect.height.toInt());
if(src.width > 300) {
src = Image.copyResize(src,width: 300 , height: 300);
}
setState(() {
   imageCroppedBytes = Image.encodeJpg(src , quality: 80);
   imagePicked = false;
   imageCropped = true;
});

【讨论】:

  • 你有一个工作存储库吗?这个答案是稀疏的,并且鉴于有些应用程序仍未迁移到空安全,您可能希望将一些参考链接放到存储库或文档中。这是我知道对我有用的答案,但我不知道在哪里可以找到 .encodeJpg 函数,因为它不属于 ImagePicker、Image 或 ExtendedImage。将不胜感激!
  • 亲爱的@rshrc 实际上我没有任何开放的存储库,但我会编辑更多以提供帮助
  • 非常感谢!!
猜你喜欢
  • 2021-07-26
  • 2021-03-17
  • 2023-03-10
  • 2022-08-18
  • 2021-04-05
  • 2022-01-18
  • 2020-10-03
  • 2020-11-28
  • 1970-01-01
相关资源
最近更新 更多