Как загрузить несколько изображений в Rest API во Flutter, используя HTTP? - PullRequest
0 голосов
/ 27 марта 2020

Я хочу загрузить несколько изображений в Rest API. Я попробовал приведенный ниже код, чтобы загрузить одно изображение в остальные API. Работает нормально , для выбора нескольких изображений я использую multi_image_picker ссылку , как я могу изменить приведенный ниже код для загрузки нескольких изображений? Спасибо

Future<String> uploadSingleImage(File file,String userid) async
  {

    final prefs = await SharedPreferences.getInstance();
    final key = 'token';
    final value = prefs.get(key ) ?? 0;

    String fileName = file.path.split("/").last;
    var stream =
    new http.ByteStream(DelegatingStream.typed(file.openRead()));

    // get file length

    var length = await file.length(); //imageFile is your image file
    Map<String, String> headers = {
      "Accept": "application/json",
      "Authorization": "Bearer $value"
    }; // ignore this headers if there is no authentication

    // string to uri
    var uri = Uri.parse(serverUrl + "/api/v1/upload_parent_image");

    // create multipart request
    var request = new http.MultipartRequest("POST", uri);

    // multipart that takes file
    var multipartFileSign = new http.MultipartFile('photo',
        stream,
        length,
        filename: fileName
    );

    // add file to multipart
    request.files.add(multipartFileSign);

    //add headers
    request.headers.addAll(headers);

    //adding params
    request.fields['id'] = userid;
   // request.fields['firstName'] = 'abc';
    // request.fields['lastName'] = 'efg';

    // send
    var response = await request.send();

    print(response.statusCode);

    // listen for response
    response.stream.transform(utf8.decoder).listen((value) {
      print(value);
    });
  }

Ответы [ 2 ]

0 голосов
/ 28 марта 2020

Ну, вы почти готовы отправлять несколько файлов одновременно, позвольте мне опубликовать код

Future<String> uploadSingleImage(File file,File file2,String userid) async
  {

    final prefs = await SharedPreferences.getInstance();
    final key = 'token';
    final value = prefs.get(key ) ?? 0;

    String fileName = file.path.split("/").last;
    var stream =
    new http.ByteStream(DelegatingStream.typed(file.openRead()));

    // get file length    
    var length = await file.length(); //imageFile is your image file
    Map<String, String> headers = {
      "Accept": "application/json",
      "Authorization": "Bearer $value"
    }; // ignore this headers if there is no authentication

    // string to uri
    var uri = Uri.parse(serverUrl + "/api/v1/upload_parent_image");

    // create multipart request
    var request = new http.MultipartRequest("POST", uri);

    // multipart that takes file
    var multipartFileSign = new http.MultipartFile('photo',
        stream,
        length,
        filename: fileName
    );

    // add file to multipart
    request.files.add(multipartFileSign);


   // Now Adding file 2 in request
   String fileName2 = file2.path.split("/").last;
    var stream2 =
    new http.ByteStream(DelegatingStream.typed(file2.openRead()));
    var lengthOfFile2 = await file2.length(); 

   // multipart that takes file
    var multipartFile2 = new http.MultipartFile('file2_key_here',
        stream2,
        lengthOfFile2,
        filename: fileName2
    );

   // add file2 to multipart
    request.files.add(multipartFile2);

    //add headers
    request.headers.addAll(headers);

    //adding params
    request.fields['id'] = userid;
   // request.fields['firstName'] = 'abc';
    // request.fields['lastName'] = 'efg';

    // send
    var response = await request.send();

    print(response.statusCode);

    // listen for response
    response.stream.transform(utf8.decoder).listen((value) {
      print(value);
    });
  }
0 голосов
/ 28 марта 2020

Вы можете передать список файлов вашему методу, l oop, чтобы создать каждый объект MultipartFile и добавить их в свой MultipartRequest

Future<String> uploadMultipleImage(List<File> files, String userid) async {
final prefs = await SharedPreferences.getInstance();
final key = 'token';
final value = prefs.get(key) ?? 0;

// string to uri
var uri = Uri.parse(serverUrl + "/api/v1/upload_parent_image");

// create multipart request
var request = new http.MultipartRequest("POST", uri);

for (var file in files) {
    String fileName = file.path.split("/").last;
    var stream = new http.ByteStream(DelegatingStream.typed(file.openRead()));

    // get file length

    var length = await file.length(); //imageFile is your image file

    // multipart that takes file
    var multipartFileSign = new http.MultipartFile('photo', stream, length, filename: fileName);

    request.files.add(multipartFileSign);
}

Map<String, String> headers = {
    "Accept": "application/json",
    "Authorization": "Bearer $value"
}; // ignore this headers if there is no authentication

//add headers
request.headers.addAll(headers);

//adding params
request.fields['id'] = userid;
// request.fields['firstName'] = 'abc';
// request.fields['lastName'] = 'efg';

// send
var response = await request.send();

print(response.statusCode);

// listen for response
response.stream.transform(utf8.decoder).listen((value) {
    print(value);
});
}
...