Flutter Dio:如何上传图片?

时间:2019-08-15 12:53:58

标签: flutter dart

我正在尝试签到邮递员,这是工作的

Postman 我想使用软件包 DIO软件包将一些图像上传到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"

Api.dart

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

View.dart

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

_image 是FILE

     

我希望这个软件包的专家可以帮助我提供此代码,并建议我上传图像。
谢谢。

完整的View.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;
    });
  }
}

6 个答案:

答案 0 :(得分:15)

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

}

答案 1 :(得分:0)

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

答案 2 :(得分:0)

嗨,文件上传有很多问题

  1. 尝试在android Api 21中运行,因为如果api在android api 21中运行,则它没有android权限,那么它也可以在上述版本上运行。

  2. 您可能无法在android以上版本中获取文件

  3. 您只需要

FormData formData = FormData.fromMap({       “ av_document”:等待MultipartFile.fromFile(_filePath,filename:        _文件名),          });

将任何文件或图像上传到服务器,还有一点需要注意

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


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

通过此过程,您可以将文件或图像上传到服务器

答案 3 :(得分:0)

以下代码将多个图像文件从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()
}

答案 4 :(得分:0)

在最新版本的 Dio 中:

它应该看起来像这样。

A/

如果没有此行。

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] Exceptionhttp_parser

答案 5 :(得分:0)

我找到了一个解决方案,我将文件上传到特定目录,该目录生成不同的相机包,需要文件路径以在提供的路径中保存 jpg 文件。

我正在获取带有路径的文件名并传递给

  DIO package

这是给文件长度问题,我已经实施了以下步骤来解决这个问题

从目录中获取带有完整路径的文件名 从路径创建一个文件

File(directoryFilePathWithExtension);

并将 File.path 传递给 dio 包

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