3

我正在尝试dio在我的颤振应用程序中使用包上传文件。我正在通过formdata. 这是我的实现:

Future<FormData> formData1() async {
    return FormData.fromMap({
      "title": "from app2",
      "description": "app upload test",
      "files": [
        for (var i = 0; i < pathNames.length; i++)
          await MultipartFile.fromFile(pathNames[i],
              filename: fileNames[i])
      ]
    });
  }

这是我发送文件的方式。

_sendToServer() async {
    Dio dio = Dio(
      BaseOptions(
        contentType: 'multipart/form-data',
        headers: {
          "Authorization": "$token",
        },
      ),
    );
    dio.interceptors.add(
        LogInterceptor(requestBody: true, request: true, responseBody: true));
    FormData formData = await formData1();
    try {
      var response = await dio.post("http://url/api/upload",
          data: formData, onSendProgress: (int send, int total) {
        print((send / total) * 100);
      });
      print(response);
    } on DioError catch (e) {
      if (e.response != null) {
        print(e.response.data);
        print(e.response.headers);
        print(e.response.request);
      } else {
        print(e.request.headers);
        print(e.message);
      }
    }
  }

中的其他字段formdata被发送到服务器,而不是multipartfile. 当我尝试从邮递员表单数据中执行相同操作时,它会正确上传。我在这里做错了吗?

4

5 回答 5

1

如果你想上传文件,你可以在调用 API 函数之前转换多部分数组,因为即使你把等待作为form data dio响应也不会等待formdata对象,或者你可以使用 MultipartFile.fromFileSync() 来摆脱等待。

让我使用我的示例以简单的方式向您展示。试着去理解。

多部分转换

List multipartArray = [];
for (var i = 0; i < pathNames.length; i++){
   multipartArray.add(MultipartFile.fromFileSync(pathNames[i], filename: 
   basename(pathNames[i])));
}

API端

static Future<Response> createPostApi(multipartArray) async {
    var uri = Uri.parse('http://your_base_url/post');
    return await Dio()
        .post('$uri',
            data: FormData.fromMap({
              "title": "from app2",
              "description": "app upload test",
              "files": multipartArray
            }))
        .catchError((e) {
      print(e.response.data);
      print(e.response.headers);
      print(e.response.request);
    });
  }
于 2020-03-09T06:19:52.750 回答
0
// here attachmentFile is File instance, which is set by File Picker

Map<String, dynamic> _documentFormData = {};

if (attachmentFile != null) {
        _documentFormData['document_file'] = MultipartFile.fromFileSync(attachmentFile.path);
}
FormData formData = FormData.fromMap(_documentFormData);

try {
      var response = await dio.post("http://url/api/upload",
          data: formData, onSendProgress: (int send, int total) {
        print((send / total) * 100);
      });
      print(response);
    } on DioError catch (e) {
      if (e.response != null) {
        print(e.response.data);
        print(e.response.headers);
        print(e.response.request);
      } else {
        print(e.request.headers);
        print(e.message);
      }
    }
于 2020-03-09T06:02:51.010 回答
0

这是我的代码,我使用了 file_picker 颤振库和 MediaType('application', 'pdf') 来确保传递给 API 的内容确实是 .pdf 文件。

import 'dart:io';
import 'package:dio/dio.dart';
import 'package:http_parser/http_parser.dart';

static Future<dynamic> uploadfile(int userid, File file, String token) async {
  var fileName = file.path.split('/').last;
  print(fileName);
  var formData = FormData.fromMap({
    'title': 'Upload Dokumen',
    'uploaded_file': await MultipartFile.fromFile(file.path,
        filename: fileName, contentType: MediaType('application', 'pdf')),
    "type": "application/pdf"
  });

  var response = await Dio().post('${urlapi}request/',
      options: Options(
          contentType: 'multipart/form-data',
          headers: {HttpHeaders.authorizationHeader: 'Token $token'}),
      data: formData);
  print(response);
  return response;
}

文件选择器:

FilePickerResult? result = await FilePicker.platform.pickFiles();
if (result != null) {
  File file = File(result.files.single.path ??'file.pdf');
  BlocProvider.of<UploadCubit>(context)
                                   .uploadFile(statelogin.user.id, file,
                                          statelogin.user.token);
}
于 2021-07-21T17:09:22.043 回答
0

用以下休息改变formdata很好

   import 'package:path/path.dart' as pathManager;
    import 'package:mime/mime.dart' as mimeManager;

FormData formdata = FormData();

 formdata.add(
          "files",
          [UploadFileInfo(img, pathManager.basename(img.path),
          contentType:
              ContentType.parse(mimeManager.lookupMimeType(img.path)))]);
于 2020-03-09T05:54:02.167 回答
0

在这里,您可以使用MultipartRequest类而不使用任何库来使用 restAPI 上传任何类型的文件。

void uploadFile(File file) async {

    // string to uri
    var uri = Uri.parse("enter here upload URL");

    // create multipart request
    var request = new http.MultipartRequest("POST", uri);

    // if you need more parameters to parse, add those like this. i added "user_id". here this "user_id" is a key of the API request
    request.fields["user_id"] = "text";

    // multipart that takes file.. here this "idDocumentOne_1" is a key of the API request
    MultipartFile multipartFile = await http.MultipartFile.fromPath(
          'idDocumentOne_1',
          file.path
    );

    // add file to multipart
    request.files.add(multipartFile);

    // send request to upload file
    await request.send().then((response) async {
      // listen for response
      response.stream.transform(utf8.decoder).listen((value) {
        print(value);
      });

    }).catchError((e) {
      print(e);
    });
  }

我使用文件选择器来选择文件。这是挑选文件的代码。

Future getPdfAndUpload(int position) async {

    File file = await FilePicker.getFile(
      type: FileType.custom,
      allowedExtensions: ['pdf','docx'],
    );

    if(file != null) {

      setState(() {

          file1 = file; //file1 is a global variable which i created
     
      });

    }
  }

这里file_picker颤振库。

于 2021-02-06T19:34:10.953 回答