[英]Graphql Apollo Server + Vue => Image Upload
我在前端使用帶有 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
});
}
應該返回路徑並將圖像保存到本地的上傳方法:
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 是一個對象。 並將它們上傳到我的本地文件夾也不起作用。 任何幫助表示贊賞並標記為已接受的答案
很高興分享您的 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;
},
},
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.