我正在研究一个Flutter web项目,FilePicker在Flutter web上返回路径为null,那么我如何创建一个可以发送到Multipart的文件,以便将其发送到Node.js或Express.js服务器?
PACKAGES REQUIRED
颤振的一面:
- 戴奥
- 文件选择器
NODEJS:
- 乘
FLUTTER - PICK A FILE
test() async {
// * Pick a File
FilePickerResult? result = await FilePicker.platform.pickFiles();
if (result != null) {
// * cast it to bytes
List<int> bytes = result.files.single.bytes!.cast();
// * Get its name, will use it later.
var name = result.files.single.name;
// * Send it to method that will make HTTP request.
_projectProvider.test(bytes, name);
}
}
FLUTTER -发出HTTP请求
import 'dart:developer';
// ignore: depend_on_referenced_packages
import 'package:http_parser/http_parser.dart';
import 'package:dio/dio.dart';
class ProjectProvider {
// * constructor
ProjectProvider() : _dio = Dio();
// * dio
late Response _response;
late final Dio _dio;
// * rest api
final _baseUrl = "http://127.0.0.1:3000";
test(List<int> bytes, String name) async {
String extension = name.split(".").last;
var formData = FormData.fromMap({
"file": MultipartFile.fromBytes(
bytes,
filename: name,
contentType: MediaType("File", extension),
),
});
_response = await _dio.post("$_baseUrl/test", data: formData);
log("test response");
log(_response.data.toString());
}
}
NODEJS SERVER - MULTER STORAGE SETTINGS
const multer = require("multer");
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, "./files/");
},
filename: function (req, file, cb) {
const uniqueSuffix = Date.now() + "-" + Math.round(Math.random() * 1e9);
let originalName = file.originalname;
let extension = originalName.split(".")[1];
cb(null, file.fieldname + "-" + uniqueSuffix + "." + extension);
},
});
const upload = multer({ storage: storage });
NODEJS SERVER - POST REQUEST HANDLER
app.route("/test").post(upload.single("file"), function (req, res) {
res.send(req.file);
});