我在前端使用Vue和vue-apollo,在后端使用带有mongodb的graphql独立Apollo Server 2和mongoose。我有一个简单的博客应用程序,其中的帖子也有一个图像。除了上传图片,一切都正常。我希望将图像上传到后端文件夹中的本地文件系统中,而仅将图像的路径保存在mongodb文档中。
突变:
async createPost(parent, args, context, info) {
//...
const {stream, filename} = await args.img
const img_path = await upload({stream, filename})
const post = await Post.save({
//img is a string in my mongo model
img: img_path,
author_name: args.user.username,
author_email: args.user.email
});
}
应该返回路径并将图像保存到本地的上载方法:
const upload = ({ stream, filename }) => {
const id = shortid.generate()
const path = `${UPLOAD_DIR}/${filename}-${id}`
new Promise((resolve, reject) =>
stream
.pipe(fs.createWriteStream(filename))
.on("finish", () => resolve(path))
.on("error", reject(Error))
);
}
即时消息错误是,在调用upload()时,流和文件名未定义,但如果我记录下来,args.img是一个对象。并且将它们上传到我的本地文件夹均无效。感谢所有帮助并将其标记为接受的答案
答案 0 :(得分:0)
最好共享您的graphql模式,以便我们可以看到您返回的类型。但是,这就是我在大多数应用程序中处理文件上传的方式。
type File {
id: ID!
filename: String!
mimetype: String!
path: String!
}
import { Schema, model } from "mongoose";
const fileSchema = new Schema({
filename: String,
mimetype: String,
path: String,
});
export default model("File", fileSchema);
const storeUpload = async ({ stream, filename, mimetype }) => {
const id = shortid.generate();
const path = `images/${id}-${filename}`;
// (createWriteStream) writes our file to the images directory
return new Promise((resolve, reject) =>
stream
.pipe(createWriteStream(path))
.on("finish", () => resolve({ id, path, filename, mimetype }))
.on("error", reject)
);
};
const processUpload = async (upload) => {
const { createReadStream, filename, mimetype } = await upload;
const stream = createReadStream();
const file = await storeUpload({ stream, filename, mimetype });
return file;
};
export default {
Mutation: {
uploadFile: async (_, { file }) => {
mkdir("images", { recursive: true }, (err) => {
if (err) throw err;
});
const upload = await processUpload(file);
// save our file to the mongodb
await File.create(upload);
return upload;
},
},
};
Here you can find an article i wrote on how to handle file uploads