flutter 如何在多部分请求中发送空文件

2w2cym1i  于 2023-01-14  发布在  Flutter
关注(0)|答案(2)|浏览(160)

我无法在flutter中使用http请求发送空白文件。服务器给我异常'500'。我还需要发送一个参数"Filename",因为它不是可选的,否则如果文件为空,我可以跳过它。
下面是代码:

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

我的意思是这样的:截图来自 Postman

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

xghobddn

xghobddn1#

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);
vddsk6oq

vddsk6oq2#

要发送空白文件,可以使用以下命令

request.files.add(http.MultipartFile.fromBytes('field-name', [],
            contentType: MediaType('image', 'png'), filename: ''));

导入此

import 'package:http_parser/http_parser.dart';
import 'package:http/http.dart' as http;

这是我的完整代码

Future<http.Response> multiPartRequest(
  {required Map<String, String> multiPartBody,
  required List<File?> multiPartFile}) async {
var url = Uri.parse("your-base-url/your-endpoint");
var request = http.MultipartRequest('POST', url);

request.fields.addAll(multiPartBody);

int cnt = 1;
for (var file in multiPartFile) {
  if (file != null) {
    String filename = file.path.split('/').last;
    request.files.add(await http.MultipartFile.fromPath(
        'file$cnt', file.path,
        filename: filename));
  } else {
    request.files.add(http.MultipartFile.fromBytes('file$cnt', [],
        contentType: MediaType('image', 'png'), filename: ''));
  }
  cnt++;
}

var streamedResponse = await request.send();
var response = await http.Response.fromStream(streamedResponse);
debugPrint(response.body);
return response; 
}

相关问题