[英]How to convert Uint8List image to File Image for upload in flutter web
我已經能夠從我的計算機中選擇一個文件並顯示在我的 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
中的theChosenImg = files[0];
,這也告訴我數據類型不匹配。
我可以將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);
},
),
],
),
],
),
),
);
}
}
Class 與發送圖像的方法
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);
});
}
}
File.fromRawPath(Uint8List uint8List);
我試圖生成一個可以同時支持設備和 web 的代碼。
因為 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 一起返回的NodeJ來獲取文件並保存它。
編輯:
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;
});
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 -.-.-.-
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.