【问题标题】:Upload file from flutter to server NodeJS using multer in node使用节点中的multer将文件从flutter上传到服务器NodeJS
【发布时间】:2021-09-16 14:08:47
【问题描述】:

我将flutter用于移动应用程序的前端,将nodeJS用于后端,我正在尝试使用multer上传照片,在后端它工作得很好,我用邮递员对其进行了测试,但是当我从发送文件时遇到问题颤抖。

颤动代码

    Future<void> getImage() async {
        final pickedFile = await picker.getImage(source: ImageSource.gallery);
    
        setState(() {
          if (pickedFile != null) {
            _image = File(pickedFile.path);
          } else {
            print('No image selected.');
          }
        });
      }
    upload(File imageFile) async {
    var stream =new http.ByteStream(DelegatingStream.typed(imageFile.openRead()));
    var length = await imageFile.length();
    var uri = Uri.parse("http://192.168.1.8:8081/products/add-product");
    var request = new http.MultipartRequest("POST", uri);
    var multipartFile = new http.MultipartFile('photo', stream, length,filename: basename(imageFile.path));
    request.files.add(multipartFile);
    var response = await request.send();
  }

 

   if(_image.path != null){
           upload(_image);
          _addProduct(context, product);
                            }

部分代码节点帖子

 router.post('/add-product', upload.single('photo'),async (req,res)=>{
    console.log(req.file);
    const product = new Product({
        name : req.body.name,
        price : req.body.price,
        detail : req.body.detail,
        quantity : req.body.quantity,
        photo : req.file.path 
    });
});

【问题讨论】:

    标签: node.js flutter multer


    【解决方案1】:

    您可以更轻松地发送字节数组,没有任何问题或任何额外的包。

    只需添加可以采用 int 数组或 unint8List 的参数,或者更好的是,您可以使用 base64 编码并将其作为字符串发送。选择文件后,只需使用 readAsBytes 并将其与您的请求正文一起发送。或者将unit8list编码成base64然后发送。在 Flutter 应用端这很简单,但您将使用 base64 解码器在服务器端处理它并保存文件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多