我正在尝试上传图片,这是代码:
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>
然后我尝试使用win photo viewer打开新保存的图像,但它显示“不支持此文件格式”,而我可以看到原始图像的内容。所以我猜我没有使用正确的方法解码字节(也许只是一个猜测)。
你们能给我一个暗示吗?
抱歉英语不好。
答案 0 :(得分:3)
在服务器端,您将保存包含 multipart 信息的HTTP请求正文。尝试使用文本编辑器打开保存的文件,您将看到如下内容:
------WebKitFormBoundaryOTIF23kDCYaWAAlc
Content-Disposition: form-data; name="myfile"; filename="photo.jpeg"
Content-Type: image/jpeg
<FF><D8><FF><E0>^@^PJFIF^@^A^A^@^@^A^@^A^......
------WebKitFormBoundaryOTIF23kDCYaWAAlc--
您需要解析请求正文以检索上传文件的真实内容。您可以使用http_server package这样做:
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);
}
});
});
}