spring,图片上传

1.html代码

<div class="line_grid">
        <div class="g_2 g_2M">
		<span class="label">电影图片:</span>
	</div>
	<div class="g_10 g_10M">
		<input id="pic" type="hidden" value="${hs.pic}" />
		<input id="uploadFile" name="uploadFile" accept=".bmp,.gif,.jpeg,.png,.jpg" type="file" οnchange="previewImagepr(this);" />
		<div id="preview"></div>
	</div>
	<div class="clear"></div>
</div>
2.js代码

var MAXWIDTH  = 100;
var MAXHEIGHT = 100;
function previewImagepr(file){
	var div = $('#preview');
	if (file.files){
		$.each(file.files,function(index,item){
			if((item.type == 'image/bmp') || (item.type == 'image/gif') || (item.type == 'image/jpeg') || (item.type == 'image/png')){ 
				//	目前仅支持这四种格式的图片 
				var fileList = [];
				imgFile = {
					file:item		//file
				};
				fileList[fileList.length] = imgFile;
				div.empty();
				div.append("<div style='width:100px;height:100px;margin:3px;border:1px solid #000;float:left;'>"
							+"<img name='imghead' >"
						  +"</div>");
				var img = $('img[name=imghead]').last();
				var reader = new FileReader();
				reader.readAsDataURL(item);
				reader.onload = function(evt){	
					img.attr('src',evt.target.result);
				}
				img.on('load',function(){	
					var rect = clacImgZoomParam(MAXWIDTH, MAXHEIGHT, this.width, this.height);
					img.attr('width',rect.width);
					img.attr('height',rect.height);
					img.css({'marginLeft':rect.left,'marginTop':rect.top});
				});
				var formdata = new FormData(this);
				for(var index in fileList){
				   	formdata.append("fileUpload"+index, fileList[index].file);
				}
			    $.ajax({
			        type:'POST',
			        url : CONTEXT_PATH + "/common/pic.do",
			        data:formdata,
			        /**
			         *必须false才会自动加上正确的Content-Type
			         */
			        contentType:false,
			        /**
			         * 必须false才会避开jQuery对 formdata 的默认处理
			         * XMLHttpRequest会对 formdata 进行正确的处理
			         */
			        processData:false,
			        success: function(data){
			        	console.log(data);
			        	$('#pic').val(data.res);
	                },
			        error:function(){
			        	alert('上传失败!');
			        }
			    });
			}
		});
	}
}
//调整图片大小
function clacImgZoomParam( maxWidth, maxHeight, width, height ){
			param = {width:0,height:0,left:0,top:0};
			if( width>maxWidth || height>maxHeight ){
				rateWidth = width / maxWidth;
				rateHeight = height / maxHeight;
				if( rateWidth > rateHeight ){
					param.width =  maxWidth;
					param.height = Math.round(height / rateWidth);
				}else{
					param.width = Math.round(width / rateHeight);
					param.height = maxHeight;
				}
			}
			//居中显示
			param.left = Math.round((maxWidth - param.width) / 2);
			param.top = Math.round((maxHeight - param.height) / 2);
			return param;
		}
2.java,server端处理

@RequestMapping("/pic.do")
	@ResponseBody
	public Parameter page(HttpServletRequest request,
			HttpServletResponse response) throws IllegalStateException,
			IOException {
		Parameter parameter = new Parameter();
		Log.info("movie图片上传");
		// 创建一个通用的多部分解析器
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
				request.getSession().getServletContext());
		// 判断 request 是否有文件上传,即多部分请求
		if (multipartResolver.isMultipart(request)) {
			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
//			Map<String, MultipartFile> files = multiRequest.getFileMap();
			Iterator<String> iter = multiRequest.getFileNames();
			while (iter.hasNext()) {
				MultipartFile file = multiRequest.getFile(iter.next());
				if (file != null) {
					String path = request.getRealPath("/") + "res/";
					String pid = UUID.randomUUID().toString().toUpperCase();
					String name = file.getOriginalFilename();
					String jpg = name.substring(name.lastIndexOf("."));
					parameter.setRes(pid+jpg);
					File localFile = new File(path+pid+jpg);
					file.transferTo(localFile);
				}
			}
		}
		return parameter;
	}
总结:这个只是简单的处理,可以拓展,如:图片压缩,多图片上传,视频上传,图片的在线简单编辑。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值