【问题标题】:How to send a blank file in multipart request如何在多部分请求中发送空白文件
【发布时间】:2020-06-04 08:40:41
【问题描述】:

我无法在 Flutter 中使用 http 请求发送空白文件。 服务器给了我例外'500'。 另外我需要发送一个参数“文件名”因为它不是可选的,否则如果文件为空我可以跳过它。

代码如下:



  final Uri _saveTaskUrl =
      Uri.parse('http://————————);

  Future addNewTask(
      {File image,
      taskName,}) async {
// Intilize the multipart request
final imageUploadRequest = http.MultipartRequest('POST', _saveTaskUrl);

// Attach the file in the request

  final mimeTypeData =
      lookupMimeType(image?.path ?? '', headerBytes: [0xFF, 0xD8])
          .split('/');

   //Error is here
//////////////////////////////////////////////////////////
   //what to do here if i want to send a blank image file
  final file = await http.MultipartFile.fromPath('FileName', image?.path ?? ''
      ,contentType: MediaType(mimeTypeData[0], mimeTypeData[1]));
////////////////////////////////////////////////////////
  imageUploadRequest.files.add( file);


imageUploadRequest.headers.addAll({
  "token": centralstate.loginData["AuthToken"],
  "clientid": centralstate.loginData["ClientId"].toString(),

});


    imageUploadRequest.fields['taskName'] = taskName;


    try {

      final streamedResponse = await imageUploadRequest.send();
      final response = await http.Response.fromStream(streamedResponse);
      if (response.statusCode != 200) {

        print(
            'Error while adding new task : ${response.statusCode} : ${response.body}');
        return 0;
      }


      print(responseData);

      return 1;
    } catch (e) {

      return 0;
    }
  }

从空白文件我的意思是这样的: 邮递员截图

我知道我可以使用 if 语句来检查文件!=null,但我明确想要发送一个空白文件。

【问题讨论】:

  • 你试过MultipartFile.fromBytes构造函数吗,零长度字节数组?
  • @RichardHeap 我试过这个:http.MultipartFile.fromBytes('FileName', [], contentType: MediaType(mimeTypeData[0], mimeTypeData[1]));
  • 发生了什么?它奏效了吗?您是否使用数据包捕获检查传输的数据。 (如果更容易捕获,您可以在任何机器上使用纯 Dart 项目进行测试。)
  • 不,它仍然给我异常 500:发生内部服务器错误。虽然感谢您的建议。由于我找不到任何解决方案,我已经告诉我的 API 开发人员将此参数设为可选。
  • @AnirudhSharma 我也有和你一样的情况,你找到解决办法了吗?

标签: http flutter dart


【解决方案1】:
http.MultipartRequest request = http.MultipartRequest(
    "POST",
    Uri.parse(baseUrl + "api/profiles/v1/update/"),
  )
    ..fields['first_name'] = firstName
    ..fields['last_name'] = lastName
    ..fields['phone'] = phone
    ..fields['full_name'] = fullName
    ..fields['country'] = 'Uzbekistan'
    ..fields['city'] = 'Tashkent'
    ..fields['date_birth'] = dateBirth!;

  if (req.image == null) {
    request.fields['image'] = '';
  } else {
    var picture = await http.MultipartFile.fromPath(
      'image',
      req.image!,
      filename: req.image!.split('/').last,
    );
    request.files.add(picture);
  }
  var response = await request.send();
  var responsed = await http.Response.fromStream(response);
  print(responsed.body);

【讨论】:

    猜你喜欢
    • 2014-01-24
    • 1970-01-01
    • 2015-08-12
    • 1970-01-01
    • 1970-01-01
    • 2016-05-14
    • 2017-11-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多