Graphql 아폴로 서버 + Vue = > 이미지 업로드
프런트엔드의 vue-apollo와 함께 Vue를 사용하고 백엔드의 mongodb에서 mongoose를 통해 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 스키마를 공유하여 반환되는 유형을 확인할 수 있으면 좋겠습니다.하지만 대부분의 앱에서 파일 업로드를 처리하는 방법은 다음과 같습니다.
graphql-displicted
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;
},
},
};
여기서 파일 업로드 처리 방법에 대한 기사를 찾을 수 있습니다.
언급URL : https://stackoverflow.com/questions/53527667/graphql-apollo-server-vue-image-upload
'programing' 카테고리의 다른 글
프로포스를 갱신할 때 VueJS 컴포넌트 데이터 속성 갱신 (0) | 2022.08.15 |
---|---|
"typedef"는 유형과 에일리어스 사이에 표준 적합성이 있습니까? (0) | 2022.08.11 |
Vue.js 앱의 vuex 스토어를 사용하여 하위 구성 요소(설정 페이지)에서 값을 설정하는 방법은 무엇입니까? (0) | 2022.08.11 |
내 컴퓨터의 Java SDK 폴더는 어디에 있습니까?우분투 12.04 (0) | 2022.08.11 |
상위 구성 요소 Vue에서 하위 구성 요소의 메서드를 호출하는 방법 (0) | 2022.08.11 |