Dart how to upload image

安稳与你 提交于 2019-11-29 15:36:46

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