我的Vue.js应用程序未将文件上传到服务器,我尝试上传文件,但无法正常工作,我什至试图登录到formData控制台,但它给了我一个空对象。我已经尝试了所有我知道的东西,但是仍然无法正常工作。我的应用使用Vue.js作为带有apollo-client的前端框架,并使用Node.js和apollo-server。
这是我的Vue.js代码:
<template>
<div id="courses__page">
<form class="signup__form" v-on:submit.prevent="AddCourse" enctype="multipart/form-data">
<div class="form-group col-md-6" >
<label >Course Picture:</label>
<input type="file" ref="file" @change="selectFile" class="file-input" />
</div>
<div v-if="selectedFile" class="form-group col-md-6" >
<img :src="image" alt="">
</div>
<button type="submit" class="btn btn-accent"> Add Courses </button>
</form>
</div>
</template>
<script>
const CREATE_COURSE = gql `
mutation CREATECOURSE_MUTATION($Picture: Upload!) {
createCourses(Picture: $Picture) {
filename
}
}
`
export default {
name:'helloworld',
data: () => ({
file:'',
image: '',
selectedFile:false
}),
methods: {
AddCourse(){
const formData = new FormData()
formData.append('file', this.file/*, this.file.name*/)
console.log(JSON.stringify(this.file))
console.log(JSON.stringify(formData))
return this.$apollo.mutate({
mutation: CREATE_COURSE,
variables: {
Picture: formData //this.file
}
}).then((result) => {
console.log(result)
this.success=true;
}).catch((error) => {
this.success=false;
console.log(error)
this.theErorMsg = JSON.parse(JSON.stringify(error.graphQLErrors[0].message)).replace(/['"]+/g, '').replace(/[\[\]']+/g,'').split("child");
})
},
selectFile(e){
this.selectedFile=true
this.file = e.target.files || e.dataTransfer.files;
if (!this.file.length)
return;
var image = new Image()
var reader = new FileReader()
var vm = this;
reader.onload = (e) => {
vm.image = e.target.result
};
reader.readAsDataURL(this.file[0])
this.file = this.file[0]
}
}
}
</script>
在我的Node.js中,这是我的架构代码:
import { gql } from 'apollo-server-express';
export default gql`
extend type Mutation {
createCourses(Picture: Upload!): fileMetadata!
}
type fileMetadata {
originalname : String
mimetype : String
encoding : String
destination : String
filename : String
path : String
size : Int
}
;
和我的解析器代码:
import { combineResolvers } from 'graphql-resolvers';
import Sequelize from 'sequelize';
import {
isAuthenticated,
} from './authorization';
export default {
Mutation: {
createCourses: combineResolvers(
isAuthenticated,
async (parent, args, { models, me }) => {
console.log('args')
},
),
}
};
,以及如何使用Apollo在Node.js应用程序中处理文件上传?这是我的server.js代码:
import cors from 'cors';
import express from 'express';
import http from 'http';
import uuidv4 from 'uuid/v4';
import { ApolloServer, gql, AuthenticationError } from 'apollo-server-express';
import DataLoader from 'dataloader';
import models, { sequelize } from './models';
import resolvers from './resolvers';
import schema from './schema';
import loaders from './loaders';
const dotenv = require('dotenv');
import {verifyJWT} from './functions/jwt'
dotenv.config();
const app = express();
app.use(cors());
const eraseDatabaseOnSync = true;
// authentication on a server level.
const getMe = async req => {
const token = req.headers['authorization'];
if (token) {
// console.log(verifyJWT(token))
return await verifyJWT(token)
}
};
const server = new ApolloServer({
introspection: true,
typeDefs: schema,
resolvers,
formatError: error => {
const message = error.message
.replace('SequelizeValidationError: ', '')
.replace('Validation error: ', '');
return {
...error,
message,
};
},
context: async({ req, connection }) => {
if (connection) {
return {
models,
loaders: {
user: new DataLoader(keys =>
loaders.user.batchUsers(keys, models),
),
},
};
}
if (req) {
const me = await getMe(req);
return {
models,
me,
secret: process.env.SECRET,
loaders: {
user: new DataLoader(keys => loaders.user.batchUsers(keys, models)),
},
};
}
}
});
server.applyMiddleware({ app, path: '/graphql' });
// what we wrapped our app in to set up the Apollo Server Subscription.
const httpServer = http.createServer(app);
server.installSubscriptionHandlers(httpServer);
const isProduction = !!process.env.DATABASE_URL;
const port = process.env.PORT || 8000;
sequelize.sync({ force: isProduction }).then(async () => {
if (isProduction) {
createUsersWithMessages(new Date());
}
httpServer.listen({ port }, () => {
console.log(`Apollo Server on http://localhost:${port}/graphql`);
});
});
console.log(JSON.stringify(this.file))
和console.log(JSON.stringify(formData))
都返回了一个空对象。