一般图片上传都是通过表单提交进行上传,而vue也是类似这种方式进行文件图片上传。
vue是通过vue-resource三方插件进行请求网络,所以首先需要导入vue-resources.js组件库。
vue是通过获取上传文件对象,存入带请求body中,带入到请求URL操作中
代码如下:
<div id="main">
<input ref="files" type="file" name="avatar" id="avatar" v-on:change="getImageFile">
<button @click="upload">上传图片</button>
</div>
js代码
new Vue({
el: '#main',
data:{
uploadImgFile:null
},
methods: {
getImageFile(e){//获取上传图片数据对象
e.preventDefault();
this.uploadImgFile = e.target.files;
},
upload: function(e) {
var data = new FormData();
data.append('avatar', this.uploadImgFile[0]);//组成格式{0: File, length: 1}
this.$http({
method: "POST",
url: "http://127.0.0.1:8089/mf-mobile/uploadImage.do",
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
},
body:data,//文件数据存入请求body中
params: {
userId: localStorage.getItem("userId"),
thirdSession: localStorage.getItem("thirdSession")
}
}).then(function(res) {
console.info(res.data);
}, function(error) {});
}
}
})
服务端接收代码
@RequestMapping(value = "/uploadImage.do", method = RequestMethod.POST)
public void uploadImage(@RequestParam(value = "avatar", required = false)CommonsMultipartFile file, HttpServletRequest request, HttpServletResponse response) {
//获取源文件
String fileName = file.getOriginalFilename();
//获取文件后缀
String suffix = fileName.substring(fileName.lastIndexOf("."), fileName.length());
//........
}