问题描述
我是新手,我正在构建的应用程序中使用ImagePicker插件。 从相机/图库中获取文件路径图像后,可以在我的应用中查看该文件路径图像。 image.path就是这样
/ storage / emulated / 0 / Android / data /.../ files / Pictures / 234d9437-8652-48de-a2b6-711b5f8b702d3492716976084944343.jpg
我需要从中获取图像“ 234d9437-8652-48de-a2b6-711b5f8b702d3492716976084944343.jpg”部分,并将其发送到后端db。我需要在发送之前进行转换。后端仅接受FileFormat中的图像。
如何从文件路径获取图像。在这种情况下,它是变量_imageURI。然后从中检索图像并将其转换为FileFormat。之后,我需要使用json POST请求将其传递给后端。
在我的json请求中,我有一个“图像”字段:我需要设置从以文件格式选择的图像中获取的值并将其设置为该值。怎么办呢? 有人可以用代码解释我吗? 非常感谢。
我的代码
File _imageURI;
Future _getimageFromCamera() async {
var petimage = await ImagePicker.pickImage(source: ImageSource.camera); //or gallery
setState(() {
_imageURI = petimage;
print(_imageURI.path);
}
}
图片浏览为
Container(
width: 120.0,height: 120.0,decoration: new Boxdecoration(
shape: BoxShape.circle,image: new decorationImage(
fit: BoxFit.cover,image: new FileImage(
_imageURI,scale: 1.0,),
Json请求
dogData = {
{
"user_email": "email@m.com,"user_token": "thisistoken","pet": {
"age": "integer","birth_date": "%d %b %Y (01 JAN 1996)","image": "!Swagger doesn't allow to put file upload. Use formdata instead of base64 in frontend module.","name": "string","sex": "string","user_id": "id"
}
}
我的API调用
final pet = await CallApi().createThePet(dogData,'pets/create');
////
Future<dynamic> createThePet(data,apiUrl) async{
var fullUrl = _baseUrl + apiUrl; // + await _getToken();
final response = await http.post(fullUrl,body: jsonEncode(data),headers: _setHeaders());
....
解决方法
您要查找的术语称为多部分。 扑朔迷离中没有明确的代码段,所以我发布了一个示例代码段。
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");
}
}
,希望这会有所帮助,我的项目运行正常 安装imagepicker,mime,http并将其导入
(,)
初始化变量
m
选择后查看显示图片
(n)
相机的图像选择器
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();
您可以使用图库或相机检出我的github以上传图像github