用文件向服务器发送请求

Posted

技术标签:

【中文标题】用文件向服务器发送请求【英文标题】:flutter post request to server with file 【发布时间】:2020-04-18 11:07:54 【问题描述】:

亲爱的,我是flutter的新手,我想将post请求从flutter发送到服务器 这是邮递员的要求

Image-Post-Request

帖子标题:

键值

接受:应用程序/json

内容类型:application/x-www-form-urlencoded

身份验证后:

熊令牌

帖子正文:

键:值

地址:地址

描述:描述

反馈:反馈

媒体:下载.png

我想从颤振中提出这个请求 这是我的代码:

File _img; // taken by camera

Map<String,String> headers = 
        'Content-Type':'application/json',
        'Authorization': 'Bearer $token',
      ;

 final msg = jsonEncode(
        "address"    : _address,
        "description": _description,
        "feedback"   : _techicalSupport,
        "media"      : _img;
       );


 try
        var response = await http.post(
          "url",
          headers: headers,
          body: msg,
        );
        print("$response.toString()");
   catch(e)
        print("$e.toString()");
    

我收到此错误: 未处理的异常:将对象转换为可编码对象失败:“_File”实例

注意媒体不是必需的,当我将它从正文中移除时,它可以工作并在数据库中创建记录

我想在正文中包含媒体。 请问我该怎么做...

【问题讨论】:

【参考方案1】:

这是我的问题的答案,我使用了 Dio 库:

  import 'package:dio/dio.dart';

    File myImage;
    List<File> _images = [];


    // to handle image and make list of images
    _handleImage()async
        File imageFile = await ImagePicker.pickImage(source: ImageSource.camera);
        if(imageFile != null)
            myImage = imageFile;
            _images.add(imageFile);
        
      



    // for post data with images
    void _submit() async 
        FormData formData = FormData();

        _images.forEach((image) async
              formData.files.addAll(
                  [
                    MapEntry(
                      "media[]",
                      await dio.MultipartFile.fromFile(image.path),
                    ),
                  ]
              );
        );

        formData.fields.add(MapEntry("address", _address),);
        formData.fields.add(MapEntry("description", _description),);
        formData.fields.add(MapEntry("feedback", _techicalSupport),);

        var response = await new Dio().post(
            postUrl,
            options: Options(
              headers: 
                "Content-Type": "application/json",
                "Authorization" : 'Bearer $token',
              
            ),
            data: formData
         );

        print("$response.toString()");
    

【讨论】:

【参考方案2】:

1.配置FilePicker库(可选步骤,您可以使用任何库选择您的文件)

然后选择文件

File file = await FilePicker.getFile();

2.配置dio库,版本here

import 'package:dio/dio.dart';

然后

FormData formData = FormData.fromMap(
 "FIELD_NAME_WEBSERVICE_HERE": await MultipartFile.fromFile(imageFile.path,filename: "anyname_or_filename"),
"FIELD_NAME_WEBSERVICE_HERE":"sample value for another field"),
              );

    var response = await Dio().post("FULL_URL_HERE", data: formData);

    print(response);

【讨论】:

感谢您的回答对我帮助很大【参考方案3】:

您需要将_img 转换为MultipartFile

    MultipartFile file=MultipartFile.fromBytes(
        'media', await filePath.readAsBytes(),
        filename: 'FILE_NAME');

    var request = http.MultipartRequest("POST", Uri.parse(url));
    if (files != null) request.files.add(file);

【讨论】:

【参考方案4】:

您应该使用MultipartRequest 发送文件。

import 'dart:io';
import 'package:http/http.dart' as http;
import 'package:http_parser/http_parser.dart';
import 'package:image_picker/image_picker.dart';
import 'dart:convert';

void send() async 
  final msg = 
    "address": "test",
    "description": "test",
    "feedback": "test",
  ;

  File _img;

  var image = await ImagePicker.pickImage(source: ImageSource.camera);

  _img = image;

  var response = await http.MultipartRequest(
      'POST', Uri.parse("url"))
    ..fields.addAll(msg)
    ..files.add(http.MultipartFile.fromBytes('image', _img.readAsBytesSync(),
        contentType: MediaType('image', 'jpeg'), filename: 'test.jpg'));


  print(response);

【讨论】:

var response = await http.MultipartRequest('POST', Uri.parse(postUrl),) ..headers["Authorization"] = "Bearer $token" ..fields['address'] = 'myaddress' ..fields['description'] = 'mydescription' ..fields['feedback'] = 'myfeedback' ..files.add(http.MultipartFile.fromBytes('image', myImage.readAsBytesSync(), contentType: MediaType('image', 'jpeg'))); response.send();图片没有上传到服务器,只发送了数据……

以上是关于用文件向服务器发送请求的主要内容,如果未能解决你的问题,请参考以下文章

在ExpressJS中,怎么发送请求到别的服务器请求数据

ajax-向服务器发送请求

如何用php向服务器发送post请求

向服务器发送请求有几种方式

uniapp发送请求服务器接收不到数据的问题

AJAX与Jqurey实现AJAX