我正在使用Node.js,Vue和Multer开发文件上传功能。
这是用Vue.js编写的前端代码
export default {
data(){
return{
selected: "How do you want to input the data?",
options: [
{ id: 1, name: 'Choose from file system' },
{ id: 2, name: 'Choose from an API' },
{ id: 3, name: 'Choose from a Database' }
],
files: []
}
},
methods: {
submitFiles(){
let formData = new FormData();
let url = axios.defaults.baseURL;
for( var i = 0; i < this.files.length; i++ ){
let file = this.files[i];
formData.append('files[' + i + ']', file);
}
axios.post( `${url}/select-files`,
formData,
{
headers: {
'Content-Type': 'multipart/form-data'
}
}
).then(function(response){
console.log('SUCCESS!!');
console.log('The response object is '+response);
})
.catch(function(){
console.log('FAILURE!!');
});
},
handleFilesUpload(){
let uploadedFiles = this.$refs.files.files;
for( var i = 0; i < uploadedFiles.length; i++ ){
this.files.push( uploadedFiles[i] );
}
console.log(this.files);
}
}
}
<div id="app" class="ui equal width left aligned padded grid stackable">
<div>
<div v-if="selected === 1">
<div class="large-12 medium-12 small-12 cell">
<input type="file" id="files" ref="files" v-on:change="handleFilesUpload()"/>
<div v-if="this.files.length > 0" class="ui small basic icon buttons">
<button class="ui button" v-on:click="submitFiles()">
<i class="upload icon">
</i>Upload
</button>
</div>
</div>
<br>
</div>
</div>
</div>
这是用Node.js编写的代码
// For cross origin resource sharing
app.use(function(req, res, next) {
res.header('Access-Control-Allow-Origin', 'http://localhost:8080');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Headers', 'Content-Type, Set-Cookie, *');
res.header('Access-Control-Allow-Credentials', 'true');
next();
})
const multer = require('multer');
let upload = multer();
app.post('/select-files', upload.single('files'), async(req, res) => {
try {
console.log(req.file);
} catch (err) {
res.sendStatus(400);
}
})
当我尝试使用Postman测试上述代码时,出现以下错误,
我需要访问从客户端发送的完整文件。我不知道我在做什么错。有人可以帮我吗?
答案 0 :(得分:1)
您要附加到formData
上的名称必须与upload.single()
中的文件名相同。
因此,对于单个文件上传,必须将formData.append('files[' + i + ']', file);
替换为formData.append('files', file);
。