8

PDF ファイルをリモート REST API に投稿する必要がありますが、一生それを理解することはできません。何をしても、サーバーは、まだオブジェクトをfileパラメーターに関連付けていないと応答します。という名前の PDF があるとしtest.pdfます。これは私がこれまでやってきたことです:

// Using an HttpClientRequest named req

req.headers.contentType = new ContentType('application', 'x-www-form-urlencoded');
StringBuffer sb = new StringBuffer();
String fileData = new File('Test.pdf').readAsStringSync();
sb.write('file=$fileData');
req.write(sb.toString());
return req.close();

write()これまでのところ、リクエストに応じたデータのほぼすべての組み合わせとエンコードを試しましたが、役に立ちませんでした。として送信してみました、 をcodeUnits使用してエンコードしてUTF8.encodeみました、 を使用してエンコードしてみましLatin1Codecた 私は困惑しています。

どんな助けでも大歓迎です。

4

3 に答える 3

9

http パッケージからMultipartRequestを使用できます。

var uri = Uri.parse("http://pub.dartlang.org/packages/create");
var request = new http.MultipartRequest("POST", url);
request.fields['user'] = 'john@doe.com';
request.files.add(new http.MultipartFile.fromFile(
    'package',
    new File('build/package.tar.gz'),
    contentType: new ContentType('application', 'x-tar'));
request.send().then((response) {
  if (response.statusCode == 200) print("Uploaded!");
});
于 2014-03-24T08:30:02.253 に答える
0

multipart/form-dataではなくヘッダーを使用してみてくださいx-www-form-urlencoded。これはバイナリデータに使用する必要があります。また、完全なreqリクエストを表示できますか?

于 2014-03-24T04:59:49.980 に答える
0
  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);
    });
  }

ファイルピッカーを使用してファイルを選択しました。これが pick ファイルのコードです。

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:12:30.537 に答える