Dart how to upload image

依然范特西╮ 提交于 2019-11-28 09:07:37

问题


I'm trying to upload an image, here's the code :

server.dart

import 'dart:io';

void main() {
  HttpServer.bind('127.0.0.1', 8080)
    .then((HttpServer server) {
      server.listen((HttpRequest request) {
        if (request.method.toLowerCase() == 'post') {
          request.fold(new BytesBuilder(), (builder, data) => builder..add(data))
          .then((BytesBuilder builder) {
            File file = new File('abc.jpg');
            file.writeAsBytes(builder.takeBytes(), mode: FileMode.WRITE)
              .then((_) {
                request.response.close();
              });
          });
        } else {
          File f = new File('test_1.html')
              ..openRead().pipe(request.response);
        }
      });
    });
}

test_1.html

<!DOCTYPE html>

<html>
  <head>
    <title>test_1</title>
  </head>

  <body>
    <form method="post" enctype="multipart/form-data">
      <input id="fileupload" name="myfile" type="file" placeholder="some file here..."/>
      <input type="submit" />
    </form>
  </body>
</html>

Then I tried to open the newly saved image using win photo viewer but it says "doesn't support this file format" while I can see the content of the original one. So I'm guessing I'm not using the right method to decode the bytes (maybe, just a guess).

Can you guys give me a hint?

Sorry for the bad english.


回答1:


On the server side you are saving the body of your HTTP request that contains multipart informations. Try to open your saved file with a text editor you will see something like :

------WebKitFormBoundaryOTIF23kDCYaWAAlc
Content-Disposition: form-data; name="myfile"; filename="photo.jpeg"
Content-Type: image/jpeg

<FF><D8><FF><E0>^@^PJFIF^@^A^A^@^@^A^@^A^......
------WebKitFormBoundaryOTIF23kDCYaWAAlc--

You need to parse request body to retrieve the real content of the uploaded file. You can do that with the http_server package like this :

import 'dart:io';
import 'package:http_server/http_server.dart';

void main() {
  HttpServer.bind('127.0.0.1', 8080)
    .then((HttpServer server) {
      server.listen((HttpRequest request) {
        if (request.method.toLowerCase() == 'post') {
          HttpBodyHandler.processRequest(request).then((body) {
            HttpBodyFileUpload fileUploaded = body.body['myfile'];
            final file = new File('abc.jpg');
            file.writeAsBytes(fileUploaded.content, mode: FileMode.WRITE)
              .then((_) {
                request.response.close();
              });
          });
        } else {
          File f = new File('upload.html')
              ..openRead().pipe(request.response);
        }
      });
    });
}


来源:https://stackoverflow.com/questions/18435920/dart-how-to-upload-image

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!