20

我正在尝试邮递员。它有效

邮差我想使用 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"

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

查看.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是文件类型

我希望有这个包的专家可以帮助我处理这个代码并建议我上传图片。
谢谢。

完整查看.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;
    });
  }
}

4

7 回答 7

38

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'];
}
于 2020-01-04T07:41:08.300 回答
27

即使这个问题是不久前提出的,我相信主要问题是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);
    
    }
    
  2. 创建_upload上传照片的方法,我用的是DioDio 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));
    }
    
  3. 在服务器端,我使用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';
    }
    
于 2020-01-15T18:54:03.597 回答
6

在最新版本的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

并进入MediaType这个包:http_parser

于 2020-09-23T03:39:41.680 回答
4

以下代码将多个图像文件从 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()
}
于 2020-09-02T06:52:50.087 回答
1

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

我正在使用路径获取文件名并传递给

  DIO package

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

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

File(directoryFilePathWithExtension);

并将 File.path 传递给 dio 包

MultipartFile.fromFile(
    File(directoryFilePathWithExtension).path,
    filename: DateTime.now().toIso8601String(),
)
于 2021-07-15T21:23:52.583 回答
0

您好,文件上传有很多问题

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

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

  3. 您只需要

FormData formData = FormData.fromMap({ "av_document": await MultipartFile.fromFile(_filePath,filename: _fileName), });

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

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


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

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

于 2019-12-23T07:26:44.497 回答
0

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

于 2019-08-15T13:00:04.043 回答