Flutter 从文件路径获取图像变量,并以flifter中的FileFormat上传到后端
我是一个新手,在我正在构建的应用程序中,我使用了ImagePicker插件。 这样,在我从照相机/多媒体资料中获取文件路径图像后,文件路径图像将在我的应用程序中查看。 image.path如下所示 /存储/仿真/0/Android/data/../files/Pictures/234d9437-8652-48de-a2b6-711b5f8b702d3492716976084944343.jpg 我需要从中获取图像“234d9437-8652-48de-a2b6-711b5f8b702d3492716976084944343.jpg”部分,并将其发送到后端数据库。我需要在发送前转换此文件。后端仅接受文件格式的图像 如何从文件路径获取图像。在本例中,它是变量_imageURI。然后从中检索图像并将其转换为文件格式。之后,我需要使用json POST请求将其传递到后端 在我的json请求中,我有一个“image”字段:我需要设置从文件格式中选择的image获得的值,并设置为。你怎么能做到这一点? 有人能用密码给我解释一下吗? 非常感谢 我的代码Flutter 从文件路径获取图像变量,并以flifter中的FileFormat上传到后端,flutter,file-format,imagepicker,Flutter,File Format,Imagepicker,我是一个新手,在我正在构建的应用程序中,我使用了ImagePicker插件。 这样,在我从照相机/多媒体资料中获取文件路径图像后,文件路径图像将在我的应用程序中查看。 image.path如下所示 /存储/仿真/0/Android/data/../files/Pictures/234d9437-8652-48de-a2b6-711b5f8b702d3492716976084944343.jpg 我需要从中获取图像“234d9437-8652-48de-a2b6-711b5f8b702d34927
File _image;
final Imagepicker = ImagePicker();
图像被视为
Json请求
import 'package:mime/mime.dart';
import 'package:http/http.dart' as http;
import 'package:http/http.dart';
import 'package:http_parser/http_parser.dart';
import 'package:image_picker/image_picker.dart';
我的API调用
final pet=wait CallApi().createThePet(dogData,'pets/create');
////
Future createThePet(数据、apiUrl)异步{
var fullUrl=_baseUrl+apiUrl;//+await\u getToken();
final response=wait http.post(fullUrl,body:jsonEncode(data),headers:_setHeaders());
....
您要查找的术语称为“多部件”。
在flatter中没有任何明确的代码片段,所以我发布了一个示例片段
Future<void> _uploadImage(File image) async {
String tempURL = https://YOUR_WEBSITE/upload";
var request = new http.MultipartRequest("POST", Uri.parse(tempURL));
request.headers["authorization"] = YOUR_TOKEN_HERE;
// prepare file to send.
var profilePhoto = http.MultipartFile(
'upload', image.readAsBytes().asStream(), image.lengthSync(),
filename: image.path);
request.files.add(profilePhoto);
try {
// send files to server.
var response = await request.send();
if (response.statusCode == 200) {
// now we will update the data with the
response.stream.bytesToString().asStream().listen((data) {
_updatePhoto(data);
});
} else {
print("res status code in upload func : ${response.statusCode}");
}
} catch (error) {
print("Error : $error");
}
Future\u上传映像(文件映像)异步{
字符串tempURL=https://YOUR_WEBSITE/upload";
var request=newhttp.MultipartRequest(“POST”,Uri.parse(tempURL));
request.headers[“authorization”]=您的令牌;
//准备要发送的文件。
var profilePhoto=http.MultipartFile(
'upload',image.readAsBytes().asStream(),image.lengthSync(),
文件名:image.path);
request.files.add(profilePhoto);
试一试{
//将文件发送到服务器。
var response=wait request.send();
如果(response.statusCode==200){
//现在,我们将使用
response.stream.bytesToString().asStream().listen((数据){
_更新照片(数据);
});
}否则{
打印(“上传函数中的res状态代码:${response.statusCode}”);
}
}捕获(错误){
打印(“错误:$Error”);
}
}希望这有帮助,我的项目运行良好 安装imagepicker、mime、http并导入它
import 'package:mime/mime.dart';
import 'package:http/http.dart' as http;
import 'package:http/http.dart';
import 'package:http_parser/http_parser.dart';
import 'package:image_picker/image_picker.dart';
初始化变量
File _image;
final Imagepicker = ImagePicker();
选择后显示图像的视图
Container(
width: 350,
height: 250,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(15.0),
border: Border.all(
color: Colors.deepOrangeAccent[400], width: 1.0)),
child: GestureDetector(
child: ClipRRect(
borderRadius: BorderRadius.circular(15.0),
child: Container(
width: 350,
height: 250,
child: _image == null
? Text('No image selected.')
: Image.file(
_image,
fit: BoxFit.cover,
),
decoration: new BoxDecoration(
borderRadius: BorderRadius.circular(10.0),
color: Colors.white,
),
),
),
onTap: () {
getImage();
},
),
),
摄像机的图像采集器
Future getImage() async {
PickedFile image =
await Imagepicker.getImage(source: ImageSource.camera, maxHeight: 1000);
setState(() {
_image = File(image.path);
});
}
提交功能
void submit(File image, String descrption) async {
try {
///Spilits the path and returns only the filename and type
final mimeTypeData =lookupMimeType(image.path, headerBytes: [0xFF, 0xD8]).split('/');
///Url of your api
final request =new http.MultipartRequest("POST", Uri.parse(Urls.ImageInsert));
///replace AreaImage with your database value
final file = await http.MultipartFile.fromPath('AreaImage',
image.path,contentType: MediaType(mimeTypeData[0], mimeTypeData[1]));
///In case there is text fields or other details use like this
request.fields['user_email'] = "Email";
request.fields['user_token'] = "thisistoken";
request.files.add(file);
StreamedResponse response = await request.send();
//waiting for response
response.stream.transform(utf8.decoder).listen((value) {
//Response can be pass with map object to alertbox
Map<String, dynamic> map = jsonDecode(value);
try {
// hide progrssbar
pr.hide();
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text("Alert"),
//here we show response message from api/or you can show your own message
here
content: Text(map['message']),
actions: [
FlatButton(
child: Text("Close"),
onPressed: () {
//Do Something here
},
)
],
);
},
);
} catch (e) {
e.toString();
}
});
}
}
}
void提交(文件图像、字符串描述)异步{
试一试{
///SPILIT路径并仅返回文件名和类型
final mimeTypeData=lookupMimeType(image.path,headerBytes:[0xFF,0xD8])。拆分('/');
///api的Url
final request=newhttp.MultipartRequest(“POST”,Uri.parse(url.ImageInsert));
///用数据库值替换AreaImage
final file=wait http.MultipartFile.fromPath('AreaImage',
path,contentType:MediaType(mimeTypeData[0],mimeTypeData[1]);
///如果有文本字段或其他详细信息,请这样使用
请求.字段['user_email']=“email”;
request.fields['user_token']=“thisistoken”;
request.files.add(文件);
StreamdResponse response=等待请求。发送();
//等待回应
response.stream.transform(utf8.decoder).listen((值){
//响应可以与映射对象一起传递到alertbox
Map Map=jsonDecode(值);
试一试{
//隐藏程序
pr.hide();
显示对话框(
上下文:上下文,
生成器:(BuildContext上下文){
返回警报对话框(
标题:文本(“警报”),
//这里我们显示来自api的响应消息/或者您可以显示自己的消息
在这里
内容:文本(映射[消息]),
行动:[
扁平按钮(
子项:文本(“关闭”),
已按下:(){
//在这里做点什么
},
)
],
);
},
);
}捕获(e){
e、 toString();
}
});
}
}
}
您可以使用gallery或camera签出my github以上传图像,因此您有一个值为:
'/storage/simulated/0/Android/data/../files/Pictures/234d9437-8652-48de-a2b6-711B5F8B702D34927169760844343.jpg'的,并且您想要“剪切”“文件名部分?如果是这样的话,你有没有检查过String
class官方文档?你是在建议我把这个字符串的行乞变成树干,然后把剩下的拿回来?即使这样,我如何将此图像转换为文件格式以上载到后端>?“我需要获取图像”234d9437-8652-48de-a2b6-711b5f8b702d3492716976084944343.jpg“部分”-您想要文件名部分,对吗?你没有说任何关于上传任何文件的事,在问题格式中道歉你有一个文件imageURI它是你的图像文件,你能解释一下你到底想要什么吗?谢谢Manish,我在研究这个问题的解决方案时也碰到了术语multipart。我将尝试一下你的例子。谢谢你的精彩解释。在我的代码中,我需要将这个图像文件传递到一个json请求体中,我已经更新了与此相关的问题,如果您能建议如何将图像文件传递到该请求体中,将非常有帮助。我没有这样做,我们使用multipart requset与其他请求体一起发送文件values@JasonWakubut我想这会对你有所帮助
Future getImage() async {
PickedFile image =
await Imagepicker.getImage(source: ImageSource.camera, maxHeight: 1000);
setState(() {
_image = File(image.path);
});
}
void submit(File image, String descrption) async {
try {
///Spilits the path and returns only the filename and type
final mimeTypeData =lookupMimeType(image.path, headerBytes: [0xFF, 0xD8]).split('/');
///Url of your api
final request =new http.MultipartRequest("POST", Uri.parse(Urls.ImageInsert));
///replace AreaImage with your database value
final file = await http.MultipartFile.fromPath('AreaImage',
image.path,contentType: MediaType(mimeTypeData[0], mimeTypeData[1]));
///In case there is text fields or other details use like this
request.fields['user_email'] = "Email";
request.fields['user_token'] = "thisistoken";
request.files.add(file);
StreamedResponse response = await request.send();
//waiting for response
response.stream.transform(utf8.decoder).listen((value) {
//Response can be pass with map object to alertbox
Map<String, dynamic> map = jsonDecode(value);
try {
// hide progrssbar
pr.hide();
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text("Alert"),
//here we show response message from api/or you can show your own message
here
content: Text(map['message']),
actions: [
FlatButton(
child: Text("Close"),
onPressed: () {
//Do Something here
},
)
],
);
},
);
} catch (e) {
e.toString();
}
});
}
}
}