【问题标题】:Processing an Image in Dart在 Dart 中处理图像
【发布时间】:2015-08-17 04:46:58
【问题描述】:

我目前正在尝试处理用户上传的服务器上的图像。我的目标是获取上传的这张图片,在服务器上对其进行处理,然后将其上传到机架空间云文件。我没有运气找到方法。我希望有人能带领我走向正确的方向。

这是我目前在服务器端处理的内容

Future < Null > handleUploadRequest(final HttpRequest httpRequest) async {
  print('handle upload -------------------------');

  var data;

  await httpRequest.fold(new BytesBuilder(), (b, d) => b..add(d)).then((builder) {
    data = builder.takeBytes();

    String encodedData = JSON.encode(data);

    int dataLength = encodedData.length;

    // Uploading image to rackspace cloud files

   // Here we have to send a request with username & api key to get an auth token
http.post(tokens, headers : {'Content-Type':'application/json'}, body: JSON.encode({"auth": {"RAX-KSKEY:apiKeyCredentials":{"username":"XXXXXXXXXXXXXXX","apiKey":"XXXXXXXXXXXXXXXXXXXXXXXXXXXXX"}}})).then((response) {
   print("Response status: ${response.statusCode}");
   print("Response body: ${response.body}");
   return response;
}).then((response){
   authResponse = JSON.decode(response.body);
   String token = authResponse['access']['token']['id'];


/////////// This is where we upload the image to Rackspace ///////

  var request = new http.MultipartRequest("PUT", Uri.parse('https://storage101.iad3.clouddrive.com/v1/MossoCloudFS_XXXXXXX/TestContainer/testimage.jpg'));
  request.headers['X-Auth-Token'] = token;
  request.headers['Content-Type'] = 'image/jpeg';

  var stream = new http.ByteStream.fromBytes(data);

  request.files.add(new http.MultipartFile('file', stream, data.length, filename: 'testfile.jpg', contentType: 'image/jpeg');
  print('requesT: ${request}');
  request.send().then((response) {
   print(response.statusCode);
   print(response.headers);
   print(response.stream);
   if (response.statusCode == 200) print("Uploaded!");
  });


//// End of Upload to Rackspace //////////

    print('Upload Complete!');
    httpRequest.response.write(data);
    await httpRequest.response.close();
}

现在唯一的问题是在https://pub.dartlang.org/packages/http中,我需要在参数content-type中调用类型MediaType。我不知道怎么称呼它。好像是班级里面的工厂?如果我不调用内容类型,那么它默认为 octet-stream,无法从 cdn 存储容器中打开。

此上传方式参考来自How can I upload a PDF using Dart's HttpClient?

【问题讨论】:

  • 我的建议会导致不同的行为吗?您能否编辑您的问题并直接在您的问题中添加错误输出。 [dart] 和 [dart-async] 标签下方有一个编辑链接。
  • 在 http.put(..) 之前放一个 return 不会让它运行。它打印它读取的字节并进入 .then((_).
  • 我在答案中添加了一个纯 async/await 实现,我认为它更容易推理。你能试试看它是否效果更好/更差/相同?

标签: dart dart-async rackspace-cloudfiles


【解决方案1】:

在http.put(...) 和httpRequest.response.close(); 之前似乎缺少return

在每次异步调用(调用返回 Future 的函数)之前使用 await 或将每个此类 Future 返回给调用者以保留执行顺序。如果没有任何这些,异步执行将被安排在以后执行,并且代码的下一行将在您调用的异步代码甚至开始之前执行。

更新纯异步/等待实现

import 'package:http/http.dart' as http;
import 'dart:async' show Future, Stream;
import 'dart:io';

Future<Null> handleUploadRequest(final HttpRequest httpRequest) async {
  print('handle upload -------------------------');
  print('httpRequest: ${httpRequest.headers}');

  var data;

  var builder = await httpRequest.fold(new BytesBuilder(), (b, d) => b..add(d));
  data = builder.takeBytes();
  print('bytes builder: ${data}');

  // Uploading image to rackspace cloud files
  var url =
      'https://storage101.dfw1.clouddrive.com/v1/{accountnumber}/{container}/';
  var response = await http.put(url,
      headers: {
        'X-Auth-Token': '{XXXXXXXXXAPI_KEYXXXXXXXXXX}',
        'Content-Type': 'image/jpeg',
        'Content-Length': '${httpRequest.headers.contentLength}',
      },
      body: data);

  print("Response status: ${response.statusCode}");
  print("Response body: ${response.body}");

  print('closing connection with data complete');
  httpRequest.response.write(data);
  await httpRequest.response.close();
}

【讨论】:

  • 更新时收到SocketException: Write failed, address = storage101.dfw1.clouddrive.com, port = 62429。这比我以前的要好得多(这是一个未处理的异常)。谢谢你:)。现在我需要弄清楚为什么会出现 SocketException 问题。
  • 我自己没有使用过cloudfiles,但是查看我找到的一些文档,除了帐户和容器之外,您可能还需要添加一个对象名称。
  • 当我上次使用他们的 php 服务时,他们有一个简单的 sdk,我只需要导入这就是为什么这对我来说很不同。虽然喜欢飞镖
  • 我明白了,至少与 PHP 相比,Dart 仍然很新。看起来最后一个 / 是多余的。我有来自docs.rackspace.com/files/api/v1/cf-devguide/content/…的信息
  • 我猜这是因为Content-length。它应该是数据的长度,而不是数据本身。 body 参数也不能以这种方式工作。这只是发送null。当我回到我的电脑上时,我会更新我的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-06-26
  • 2020-01-15
  • 2019-02-17
  • 2020-12-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多