我想使用 Package DIO Package将一些图像上传到 rest-api ,我是这个包的新手(我将此包仅用于 CRUD 操作),并且在上传图像操作时遇到问题。
我已经在阅读文档,但没有看到上传图片。我正在尝试此代码(参考文档)并遇到一些错误:
error:FileSystemException
message :"Cannot retrieve length of file"
OSError (OS Error: No such file or directory, errno = 2)
"File: '/storage/emulated/0/Android/data/com.example.mosque/files/Pictures/scaled_IMG_20190815_183541.jpg'"
Type (FileSystemException)
message:FileSystemException: Cannot retrieve length of file, path = 'File: '/storage/emulated/0/Android/data/com.example.mosque/files/Pictures/scaled_IMG_20190815_183541.jpg'' (OS Error: No such file or directory, errno = 2)
DioErrorType (DioErrorType.DEFAULT)
name:"DioErrorType.DEFAULT"
Run Code Online (Sandbox Code Playgroud)
Future uploadImage({dynamic data,Options options}) async{
Response apiRespon = await dio.post('$baseURL/mahasiswa/upload/',data: data,options: options);
if(apiRespon.statusCode== 201){
return apiRespon.statusCode==201;
}else{
print('errr');
return null;
}
}
Run Code Online (Sandbox Code Playgroud)
void uploadImage() async {
FormData formData = FormData.from({
"name_image": _txtNameImage.text,
"image": UploadFileInfo(File("$_image"), "image.jpg")
});
bool upload =
await api.uploadImage(data: formData, options: CrudComponent.options);
upload ? print('success') : print('fail');
}
Run Code Online (Sandbox Code Playgroud)
_image是文件类型
我希望这个包的专家可以帮助我处理这个代码并建议我上传图片。
谢谢。
import 'dart:io';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:mosque/api/api_mosque.dart';
class UploadImage extends StatefulWidget {
@override
_UploadImageState createState() => _UploadImageState();
}
class _UploadImageState extends State<UploadImage> {
ApiHelper api = ApiHelper();
File _image;
TextEditingController _txtNameImage = TextEditingController();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
leading: IconButton(
icon: Icon(Icons.arrow_left),
onPressed: () => Navigator.pop(context, false),
),
actions: <Widget>[
IconButton(
icon: Icon(Icons.file_upload),
onPressed: () {
uploadImage();
},
)
],
),
body: _formUpload(),
);
}
Widget _formUpload() {
return SingleChildScrollView(
scrollDirection: Axis.vertical,
child: Column(
children: <Widget>[
TextField(
controller: _txtNameImage,
keyboardType: TextInputType.text,
decoration: InputDecoration(hintText: "Nama Image"),
maxLength: 9,
textAlign: TextAlign.center,
),
SizedBox(
height: 50.0,
),
Container(
child: _image == null
? Text('No Images Selected')
: Image.file(_image),
),
SizedBox(
height: 50.0,
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
RaisedButton(
child: Icon(Icons.camera),
onPressed: () => getImageCamera(),
),
SizedBox(
width: 50.0,
),
RaisedButton(
child: Icon(Icons.image),
onPressed: () => getImageGallery(),
)
],
)
],
),
);
}
void uploadImage() async {
FormData formData = FormData.from({
"name_image": _txtNameImage.text,
"image": UploadFileInfo(File("$_image"), "image.jpg")
});
bool upload =
await api.uploadImage(data: formData, options: CrudComponent.options);
upload ? print('success') : print('fail');
}
getImageGallery() async {
var imageFile = await ImagePicker.pickImage(source: ImageSource.gallery);
setState(() {
_image = imageFile;
});
}
getImageCamera() async {
var imageFile = await ImagePicker.pickImage(source: ImageSource.camera);
setState(() {
_image = imageFile;
});
}
}
Run Code Online (Sandbox Code Playgroud)
Nhậ*_*rần 30
在Dio 最新版本中,UploadFileInfo方法已被MultipartFile类取代。这里是如何使用发布图像、视频或任何文件的方式:
Future<String> uploadImage(File file) async {
String fileName = file.path.split('/').last;
FormData formData = FormData.fromMap({
"file":
await MultipartFile.fromFile(file.path, filename:fileName),
});
response = await dio.post("/info", data: formData);
return response.data['id'];
}
Run Code Online (Sandbox Code Playgroud)
Sed*_*ush 21
即使这个问题是在不久前提出的,我相信主要问题是size图像的问题,尤其是Laravel. Flutter Image Picker库提供了一些减小图像大小的功能,我通过以下步骤解决了这个问题:
创建一个获取图像的方法,我正在使用Camera捕获照片
Future getImage() async {
File _image;
final picker = ImagePicker();
var _pickedFile = await picker.getImage(
source: ImageSource.camera,
imageQuality: 50, // <- Reduce Image quality
maxHeight: 500, // <- reduce the image size
maxWidth: 500);
_image = _pickedFile.path;
_upload(_image);
}
Run Code Online (Sandbox Code Playgroud)
_upload上传照片的创建方法,我使用的是Dio包Dio包
void _upload(File file) async {
String fileName = file.path.split('/').last;
FormData data = FormData.fromMap({
"file": await MultipartFile.fromFile(
file.path,
filename: fileName,
),
});
Dio dio = new Dio();
dio.post("http://192.168.43.225/api/media", data: data)
.then((response) => print(response))
.catchError((error) => print(error));
}
Run Code Online (Sandbox Code Playgroud)
在服务器端,我使用Laravel Laravel,我处理请求如下
public function store(Request $request)
{
$file = $request->file('file');
$extension = $file->getClientOriginalExtension();
$fullFileName = time(). '.'. $extension;
$file->storeAs('uploads', $fullFileName, ['disk' => 'local']);
return 'uploaded Successfully';
}
Run Code Online (Sandbox Code Playgroud)
Doa*_*Bui 19
在最新版本的Dio中:
它应该看起来像这样。
String fileName = imageFile.path.split('/').last;
FormData formData = FormData.fromMap({
"image-param-name": await MultipartFile.fromFile(
imageFile.path,
filename: fileName,
contentType: new MediaType("image", "jpeg"), //important
),
});
Run Code Online (Sandbox Code Playgroud)
如果没有这一行。
contentType: new MediaType("image", "jpeg")
Run Code Online (Sandbox Code Playgroud)
也许会导致错误:DioError [DioErrorType.RESPONSE]: Http status error [400] Exception
并MediaType进入这个包:http_parser
以下代码将多个图像文件从 dio 客户端上传到 golang 服务器。
Run Code Online (Sandbox Code Playgroud)FormData formData = FormData.fromMap({ "name": "wendux", "age": 25, "other" : "params", }); for (File item in yourFileList) formData.files.addAll([ MapEntry("image_files", await MultipartFile.fromFile(item.path)), ]); Dio dio = new Dio()..options.baseUrl = "http://serverURL:port"; dio.post("/uploadFile", data: formData).then((response) { print(response); }).catchError((error) => print(error));
Run Code Online (Sandbox Code Playgroud)package main import ( "fmt" "io" "net/http" "os" ) func uploadFile(w http.ResponseWriter, r *http.Request) { err := r.ParseMultipartForm(200000) if err != nil { fmt.Fprintln(w, err) return } formdata := r.MultipartForm files := formdata.File["image_files"] for i, _ := range files { file, err := files[i].Open() defer file.Close() if err != nil { fmt.Fprintln(w, err) return } out, err := os.Create("/path/to/dir/" + files[i].Filename) defer out.Close() if err != nil { fmt.Fprintf(w, "Unable to create the file for writing. Check your write access privilege") return } _, err = io.Copy(out, file) if err != nil { fmt.Fprintln(w, err) return } fmt.Fprintf(w, "Files uploaded successfully : ") fmt.Fprintf(w, files[i].Filename+"\n") } } func startServer() { http.HandleFunc("/uploadFile", uploadFile) http.ListenAndServe(":9983", nil) } func main() { fmt.Println("Server starts!") startServer() }
| 归档时间: |
|
| 查看次数: |
33056 次 |
| 最近记录: |