【问题标题】:Conver Uint8List to file in flutterweb在flutter web中将Uint8List转换为文件
【发布时间】:2022-08-18 22:32:24
【问题描述】:

嗨,我在 Flutter Web 中上传图像并将其发送到服务器时遇到问题

我需要向我们发送文件类型的图像到服务器

在我问之前,我会告诉你我正在努力的代码

import \'dart:html\';
import \'dart:typed_data\';
import \'package:flutter/material.dart\';
import \'package:image_picker/image_picker.dart\';
import \'package:provider/provider.dart\';
import \'package:web_checkup/model/provider/reservation_provider.dart\';

class CompanionImage extends StatefulWidget {
  const CompanionImage({Key? key}) : super(key: key);

  @override
  State<CompanionImage> createState() => _CompanionImageState();
}

class _CompanionImageState extends State<CompanionImage> {
  late ReservationPvd reservationPvd = context.read<ReservationPvd>();
  Uint8List webImage = Uint8List(8);
  bool uploaded = false;

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Container(
        margin: EdgeInsets.only(bottom: 20),
        decoration: BoxDecoration(borderRadius: BorderRadius.circular(100)),
        child: Stack(
          children: <Widget>[
            InkWell(
              highlightColor: Colors.transparent,
              splashColor: Colors.transparent,
              onTap: () => pickImage(),
              child: Container(
                height: 120,
                width: 120,
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(100.0),
                ),
                child: uploaded ? Image.memory(webImage) : Image.asset(\'assets/images/paw.png\'),
              ),
            ),
            Positioned(
              bottom: 0,
              right: 0,
              child: Container(
                width: 40,
                height: 40,
                decoration: BoxDecoration(
                  shape: BoxShape.circle,
                  color: Colors.white,
                  border: Border.all(color: Color(0xFFe0e0e0)),
                ),
                padding: EdgeInsets.all(0),
                alignment: Alignment.center,
                child: IconButton(
                  icon: Icon(Icons.camera_alt, size: 20, color: Color(0xFFaaaaaa)),
                  onPressed: () => pickImage(),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  pickImage() async {
    final ImagePicker picker = ImagePicker();
    XFile? image = await picker.pickImage(source: ImageSource.gallery);
    var f = await image!.readAsBytes();
    setState(() {
      webImage = f;
      uploaded = true;
    });
    reservationPvd.updateInfo(\'imageFile\', webImage);
  }
}

所以我想做的就是把 Xfile 变成 File 像下面的代码

File _file = image 

和其他事情太使 Uint8List 归档

File _file = webImage

像这样

我已经用谷歌搜索了 4 天,但我找不到 在 Flutterweb 中使 UintList 既不是 XFile 也不是 File 的一些示例

有谁知道如何在 Flutter Web 中转换文件类型?

p.s 我已经尝试过 Universal_io 或...一些其他包,Flutter 版本是 3.0.5

标签: flutter dart flutter-web dart-html uint8array


【解决方案1】:

为什么需要将其解析为 File,只需使用 XFile。当上传到多部分时,只需从 XFile 获取字节即可上传。

【讨论】:

    【解决方案2】:
            I have solved this issue by using https://pub.dev/packages/file_picker
              
    
        static  PlatformFile objFile = null;
                  static  Uint8List uInt8List=null;
                 static chooseFileUsingFilePicker() async {
                    //-----pick file by file picker,    
                    var result = await FilePicker.platform.pickFiles(
                    withData: true,
                    );
                   // var result =await ImagePicker().pickImage(source: 
              ImageSource.gallery);
                
                    if (result != null) {
                     objFile = result.files.single;
                    debugPrint('result====>${result.toString()}'); 
    uInt8List=result.files.first.bytes;
                // List<int> list = objFile.readStream.cast();
                return   uInt8List;
                }
                return null;
              }    
    
     static  Future<String> uploadSelectedFile() async {
        String endPoint='add ur endpoint';
        String param='add ur param';
        Stream<List<int>> stream;
      if(uInt8List!=null)  {
        stream= Stream.value(
    
            List<int>.from(uInt8List),
          );
        }
     
        //---Create http package multipart request object
        final request = http.MultipartRequest(
          POST,
          Uri.parse('your api goes here'),
        );
        // //-----add other fields if needed
        // request.fields["id"] = "abc";
    
        //-----add selected file with request
        request.files.add(new http.MultipartFile(
            param,uInt8List!=null?stream: objFile.readStream, objFile.size,
            filename: objFile.name));
    
    
        //-------Send request
        var resp =await callApi(PUT, endPoint, request, true);
        print(resp);
    
        if (resp != null) {
          print(jsonDecode(resp.body)['url']);
    
        return jsonDecode(resp.body)['url'] ?? '';
        }
        //-------Your response
      //  print(result);
    
        return null;
      }
    

    【讨论】:

      猜你喜欢
      • 2021-07-26
      • 2020-06-15
      • 2020-03-06
      • 2019-05-30
      • 2020-07-25
      • 2020-05-20
      • 2021-01-28
      • 2022-10-05
      • 2018-07-16
      相关资源
      最近更新 更多