Vue上传文件或图片摘要

一般图片上传都是通过表单提交进行上传,而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());
       //........
}

 

转载于:https://my.oschina.net/u/2251646/blog/1438984

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值