mai*_*n.c 5 javascript apollo vue.js graphql vuejs2
我在前端使用带有 vue-apollo 的 Vue,在后端使用带有 mongodb 的 graphql 独立 Apollo Server 2。我有一个简单的博客应用程序,其中的帖子也有一个图像。除了上传图像外,一切正常。我希望将图像上传到我后端文件夹中的本地文件系统,并且只有保存在我的 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
});
}
Run Code Online (Sandbox Code Playgroud)
应该返回路径并将图像保存到本地的上传方法:
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))
);
}
Run Code Online (Sandbox Code Playgroud)
我得到的错误是在调用 upload() 时流和文件名未定义,但如果我记录它,args.img 是一个对象。并将它们上传到我的本地文件夹也不起作用。任何帮助表示赞赏并标记为已接受的答案
小智 0
最好分享您的 graphql 架构,以便我们可以看到您返回的类型。但是,这是我在大多数应用程序中处理文件上传的方式。
type File {
id: ID!
filename: String!
mimetype: String!
path: String!
}
Run Code Online (Sandbox Code Playgroud)
type File {
id: ID!
filename: String!
mimetype: String!
path: String!
}
Run Code Online (Sandbox Code Playgroud)
import { Schema, model } from "mongoose";
const fileSchema = new Schema({
filename: String,
mimetype: String,
path: String,
});
export default model("File", fileSchema);
Run Code Online (Sandbox Code Playgroud)
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)
);
};
Run Code Online (Sandbox Code Playgroud)
const processUpload = async (upload) => {
const { createReadStream, filename, mimetype } = await upload;
const stream = createReadStream();
const file = await storeUpload({ stream, filename, mimetype });
return file;
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
583 次 |
| 最近记录: |