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

2019-12-31 21:22:12 +08:00
 hhh798

问题是: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;
3594 次点击
所在节点    程序员
3 条回复
cnbattle
2019-12-31 21:49:58 +08:00
不会 flutter, 无责任建议:指定 header from-data, 参考 https://www.cnblogs.com/52fhy/p/5436673.html
middle2000
2019-12-31 22:14:52 +08:00
laravel
2020-01-01 10:19:18 +08:00
dio 有文件上传的

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/634041

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX