FlutterDio:如何上传图片?

tf7tbtn2  于 2022-12-14  发布在  Flutter
关注(0)|答案(8)|浏览(181)

我在试《 Postman 》,效果很好
x1c 0d1x我想上传一些图像到rest-api使用包DIO包,我是新的这个包(我使用这个包只是为了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"

API.省道

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;
      }
}

查看省道

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');
  }

_图像是FILE类型

我希望谁Maven与这个软件包可以帮助我与这个代码,并建议我上传图片。

  • 谢谢-谢谢

完整视图.dart代码

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;
    });
  }
}
hc2pp10m

hc2pp10m1#

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'];
}
wgxvkvu9

wgxvkvu92#

即使这个问题是问了一段时间前,我相信主要问题是图像的size,特别是与Laravel . Flutter Image Picker库提供了一些功能,以减少图像的大小,我解决了它与以下步骤:
1.创建一个方法来获取图像,我使用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);

}

1.创建_upload方法来上传照片,我使用的是Dio包Dio Package

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));
}

1.在服务器端,我使用LaravelLaravel,我按如下方式处理请求

public function store(Request $request)
{
    $file = $request->file('file');

    $extension = $file->getClientOriginalExtension();

    $fullFileName = time(). '.'. $extension;
    $file->storeAs('uploads', $fullFileName,  ['disk' => 'local']);

    return 'uploaded Successfully';
}
ivqmmu1c

ivqmmu1c3#

在最新版本的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
  ),
});

如果没有这条线。

contentType: new MediaType("image", "jpeg")

也许这会引起一个错误:DioError [DioErrorType.RESPONSE]: Http status error [400] Exception
并在此软件包中获得MediaTypehttp_parser

yhuiod9q

yhuiod9q4#

下面的代码将多个图像文件从dio客户端上传到golang服务器。

  1. dioclient.dart
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));
  1. golangServer.go
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()
}
ukdjmx9f

ukdjmx9f5#

我找到了一个解决方案,我上传文件的特定目录,这是生成不同的相机包,需要文件路径保存在提供的路径jpg文件。
我正在用路径获取文件名并传递给

DIO package

这是给文件长度的问题,我已经实现了以下步骤来解决这个问题
从目录中获取具有完整路径的文件名从路径中创建文件

File(directoryFilePathWithExtension);

并将File.path传递给dio包

MultipartFile.fromFile(
    File(directoryFilePathWithExtension).path,
    filename: DateTime.now().toIso8601String(),
)
r7s23pms

r7s23pms6#

如果您正在使用内存映像,请使用UploadFileInfo.fromBytes(上面的错误消息显示您的文件无效且不存在)。

0yg35tkg

0yg35tkg7#

您好,文件上载中存在许多问题
1.尝试在android API 21中,因为它没有android权限,如果api在android api 21中工作,那么它也将在以上版本中工作。
1.你可能无法在上述Android版本中获得该文件
1.你只需要
表单数据=表单数据。从Map({“av_document”:等待多部分文件。fromFile(文件路径,文件名:_文件名),});
上传任何文件或图像到服务器,还有一件事要注意

_filePaths = await FilePicker.getMultiFilePath(type: _pickingType, 
        fileExtension: _extension);

        _fileName = _filePath.split('/').last

通过使用这个过程你可以上传文件或图像到服务器

vfh0ocws

vfh0ocws8#

我正在使用
dio: ^4.0.6(用于上传)
flutter_native_image: ^0.0.6+1(用于缩小图像尺寸)
减小文件大小

File? compressedFile = profileImage.value == null
      ? null
      : await FlutterNativeImage.compressImage(
          profileImage.value?.path ?? '',
          quality: 20,
          percentage: 60);

dio表单数据Map

var formData = dio.FormData.fromMap({
    "name": input['name']!.text,
    "profile_pic": await dio.MultipartFile.fromFile(compressedFile.path),
    "birth_date": input['dob']!.text,})

请求-〉

response = await _dio.post(url, data: formData);

相关问题