Dart how to upload image

后端 未结 1 726
梦谈多话
梦谈多话 2020-12-21 07:57

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

server.dart

import \'dart:io\';

void ma         


        
相关标签:
1条回答
  • 2020-12-21 08:22

    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);
            }
          });
        });
    }
    
    0 讨论(0)
提交回复
热议问题