0

我正在尝试使用颤振将文件发送到服务器,但它返回此错误:

Unhandled Exception: type 'List<File>' is not a subtype of type 'String' in type cast

代码

I've commented code below for better understanding

late List<File> newDoc = [];

// Select files
ElevatedButton(
    onPressed: () async {
        FilePickerResult? result = await FilePicker.platform.pickFiles(
            allowMultiple: true
            type: FileType.custom,
            allowedExtensions: ['jpg', 'pdf', 'doc', 'docx', 'ppt', 'pptx'],
        );
        if(result != null) {
            // Not sure if I should only get file path or complete data (this was in package documentation)
            List<File> files = result.paths.map((path) => File(path!)).toList();
            newDoc = files;
        } else {
            // User canceled the picker
        }
    },
    child: Text('Select Files'),
),

SizedBox(height: 15.0),

// Send files to server
ElevatedButton(
    onPressed: () async {

        //save
        var response = await http.post(
            Uri.parse('https://example.come/upload/${args.id}'),
            body: {
                'documents': newDoc,  // send array of my selected files to server
            },
            headers: {
                HttpHeaders.authorizationHeader: '$userToken',
                HttpHeaders.acceptHeader: 'application/json'
            },
        );

        print('request::: $response');


        // if (response.statusCode == 200) {
        //   .....
        // } else {
        //   .....
        // }
        //save

    },
    child: Text('Save'),
),

有什么建议么?

更新

我已将我的 http 请求更改为下面的代码,但我的服务器收到空正文(请求不会将我的文件发送到后端)

var request = http.MultipartRequest('POST', uri);
request.headers['authorization'] = '$userToken';
request.headers['acceptHeader'] = 'application/json';
newDoc.map((k) async {
    request.files.add(await http.MultipartFile.fromPath(
    'documents', k.path
    ));
});
var response = await request.send();
var response2 = await http.Response.fromStream(response);
print('request::: ${response2.statusCode}');
print('request::: ${response2.body}'); // return as []
4

2 回答 2

0

您的邮寄电话应如下所示

var response = await http.post(
    Uri.parse('https://example.come/upload/${args.id}'),
    body: {
        'documents': newDoc.map((e) => e.path).toList().join(', '),
    },
    headers: {
        HttpHeaders.authorizationHeader: '$userToken',
        HttpHeaders.acceptHeader: 'application/json'
    },
);

newDoc 变量是文件列表,因此使用将文件列表转换为字符串(路径)列表newDoc.map((e) => e.path).toList().join(', ')

于 2021-06-21T06:12:06.187 回答
0

你必须使用MultipartRequest上传文件。例如:

var uri = Uri.parse('https://example.com/create');
var request = http.MultipartRequest('POST', uri)
  ..fields['user'] = 'nweiz@google.com'
  ..files.add(await http.MultipartFile.fromPath(
      'package', 'build/package.tar.gz',
      contentType: MediaType('application', 'x-tar')));
var response = await request.send();
if (response.statusCode == 200) print('Uploaded!');

所以对你来说是这样的:

final request = net.MultipartRequest("post", Uri.parse("https://example.come/upload/${args.id}"));
for (final file in files) {
  request.files.add(await MultipartFile.fromPath(file.uri.pathSegments.last, file.path));
}
request.headers[HttpHeaders.authorizationHeader] = '$userToken';
request.headers[HttpHeaders.acceptHeader] = 'application/json';

final response = await request.send();

file.uri.pathSegments.last是一个文件名。

于 2021-06-21T05:25:36.107 回答