Dart how to upload image

1.8k Views Asked by At

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

There are 1 best solutions below

2
On BEST ANSWER

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);
        }
      });
    });
}