V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
• 请不要在回答技术问题时复制粘贴 AI 生成的内容
hhh798
V2EX  ›  程序员

求助, flutter 上传文件,搞了一天没解决

  •  
  •   hhh798 · 2019-12-31 21:22:12 +08:00 · 3612 次点击
    这是一个创建于 1808 天前的主题,其中的信息可能已经有所发展或是发生改变。

    问题是:flutter 客户端上传的文件后台取不到,但是用 postman 提交没有问题。。。 这个问题搞了一天了,请会 flutter 的帮忙看看

    这是 flutter 上传文件的代码

    try {
        SharedPreferences sp = await SharedPreferences.getInstance();
        File file = await ImagePicker.pickImage(source: source);
        Directory temp = await getTemporaryDirectory();
    
        File upload = await compressImage(file, temp);
    
        if (file == null) return null;
        print('$baseUrl/api/v1/upload?type=$type');
    
        http.MultipartRequest request = http.MultipartRequest(
            'POST', Uri.parse('$baseUrl/api/v1/upload?type=$type'));
        request.files.add(await http.MultipartFile.fromPath(
          'image',
          upload.path,
        ));
        request.headers.addAll({
          'Authorization': 'Bearer ${sp.getString('token')}',
        });
        print(sp.getString('token'));
        var response = await request.send();
    
        print(response.statusCode);
        if (response.statusCode == 200) {
          print(String.fromCharCodes(await response.stream.toBytes()));
          Map result =
              json.decode(String.fromCharCodes(await response.stream.toBytes()));
          if (result['success']) {
            return result['data']['image_src'];
          } else {
            showToastMessage(result['message']);
          }
        } else {
          print(response.statusCode);
          throw '出错了';
        }
      } catch (e) {
        print(e);
      }
      
    

    后台是用的 eggjs

    这是 controler 代码

    "use strict";
    
    const Controller = require("egg").Controller;
    
    class ImageController extends Controller {
      async upload() {
        const ctx = this.ctx;
    
        const type = ctx.query.type;
        const userId = ctx.auth.userId;
        const images = ctx.request.files;
    
        const result = await ctx.service.api.v1.image.upload(type, userId, images);
    
        ctx.body = result;
      }
    }
    
    module.exports = ImageController;
    

    这是 service 代码

    "use strict";
    
    const pump = require("pump");
    const fs = require("fs");
    const path = require("path");
    const Service = require("egg").Service;
    
    class ImageService extends Service {
      async upload(type, userId, images) {
        const ctx = this.ctx;
    
        try {
          const date = new Date();
          const secondaryDir =
            type === "post"
              ? `${date.getFullYear()}${date.getMonth() + 1}${date.getDate()}`
              : "avatars";
          const baseDir = `/srv/www/static/upload/images/${
            this.app.config.env === "test" || this.app.config.env === "local"
              ? "test"
              : "prod"
          }`;
          const targetDir = `${baseDir}/${secondaryDir}`;
          if (!fs.existsSync(targetDir)) {
            fs.mkdirSync(targetDir);
          }
    
          for (const image of images) {
            const imagename = `${userId}-${new Date().getTime()}${path
              .extname(image.filename)
              .toLowerCase()}`;
            const targetPath = path.join(baseDir, secondaryDir, imagename);
    
            const source = fs.createReadStream(image.filepath);
            const target = fs.createWriteStream(targetPath);
            await pump(source, target);
    
            const image_record = await ctx.model.Upload.create({
              uploader_id: userId,
              file_url: targetPath,
              created_at: Date.now()
            });
    
            return {
              success: true,
              data: {
                image_src: `${image_record.dataValues.id}`
              }
            };
          }
        } catch (e) {
          console.log(e);
          return {
            success: false,
            message: "服务器异常"
          };
        } finally {
          // delete those request tmp files
          await ctx.cleanupRequestFiles();
        }
      }
    
    }
    
    module.exports = ImageService;
    
    3 条回复    2020-01-01 10:19:18 +08:00
    cnbattle
        1
    cnbattle  
       2019-12-31 21:49:58 +08:00 via Android
    不会 flutter, 无责任建议:指定 header from-data, 参考 https://www.cnblogs.com/52fhy/p/5436673.html
    middle2000
        2
    middle2000  
       2019-12-31 22:14:52 +08:00
    laravel
        3
    laravel  
       2020-01-01 10:19:18 +08:00
    dio 有文件上传的
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   984 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 20ms · UTC 18:42 · PVG 02:42 · LAX 10:42 · JFK 13:42
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.