java实现文件上传功能——依赖Spring中的CommonsMultipartFile类

功能简介:

利用Spring框架中的CommonsMultipartFile类实现文件的上传功能。

依赖的jar包:

spring-web-3.2.6.RELEASE.jar

CommonsMultipartFile类的简介:
实现步骤:
<1>为某个按钮定义点击上传事件

 $("img").bind("click",function (e) {
       window.open("uploadFile.jsp?num=111", "上传图片",
       "height=400,width=600,toolbar=no,menubar=no,scrollbars=yes,resizable=no,location=no,status=yes,top=50,left=" +($(window).width() - 600) / 2 );
});

<2>上传页面uploadFile.jsp

<body>
    <div id="fileUploadOpen"  region="center" style="width: 450px;height: 100px;margin:20px 70px;">
        <form action="uploadExcelImageFile.action" method="post" enctype="multipart/form-data" id="fileForm">
            <input type="file" name="myFile1" id="myFile" onchange="javascript:setImagePreview();">
            <br>
            <br>
            <input type="submit" value="提交" id="submitFile"/>
            <input type="hidden" value="${param.imagePath}" name="imagePath" id="imagePath"/>
        </form>
  </div>
  <div id="localImag" style=" width: 520px; height: 250px; margin: 2px 30px;text-align: center">
      <img id="preview" src=""  style="display: none;width: 515px; height: 240px;">
  </div>
 </body>
 <script type="text/javascript">
	$(function(){ 
         $("#fileForm").ajaxForm({ 
             //定义返回JSON数据,还包括xml和script格式 
             dataType:'json',
             beforeSend: function() { 
                 //表单提交前做表单验证 
                 var myFile=$("#myFile").val();
					if(isEmpty(myFile)){
					alert("请上传文件");
					return;
				}                 
             }, 
             success: function(data) { 
                 //提交成功后调用 
                 var fileName = data.fileName;
                 var fileNewPath = data.fileNewPath;
                 console.log("==============="+fileNewPath);
                 $("#fileName").val(fileName);
                 console.log("======"+$("#imagePath").attr("value"));
                 var imagePath = $("#imagePath").attr("value");
                 window.opener.$("#"+imagePath).attr("imageFilePath",fileNewPath);
                 window.opener.$("#"+imagePath).attr("src","onlineEditExcelPic.action?filePath="+fileNewPath);
               	 alert("上传成功");
               	 window.close();
             }
         }); 
     }); 
     //下面用于图片上传预览功能
function setImagePreview(avalue) {
	var docObj=document.getElementById("myFile");

	var imgObjPreview=document.getElementById("preview");
	if(docObj.files &&docObj.files[0])
	{
		//火狐下,直接设img属性
		imgObjPreview.style.display = 'block';
		imgObjPreview.style.width = '510px';
		imgObjPreview.style.height = '240px';
		//imgObjPreview.src = docObj.files[0].getAsDataURL();

		//火狐7以上版本不能用上面的getAsDataURL()方式获取,需要一下方式
		imgObjPreview.src = window.URL.createObjectURL(docObj.files[0]);
	}
	else
	{
		//IE下,使用滤镜
		docObj.select();
		var imgSrc = document.selection.createRange().text;
		var localImagId = document.getElementById("localImag");
		//必须设置初始大小
        imgObjPreview.style.display = 'block';
		localImagId.style.width = "510px";
		localImagId.style.height = "240px";
		//图片异常的捕捉,防止用户修改后缀来伪造图片
	try{
		localImagId.style.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)";
		localImagId.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = imgSrc;
	}
	catch(e)
	{
		alert("您上传的图片格式不正确,请重新选择!");
		return false;
	}
	imgObjPreview.style.display = 'none';
	document.selection.empty();
}
return true;
}
  </script>

<3>后台处理逻辑

@RequestMapping("/uploadExcelImageFile.action")
	public @ResponseBody
	Map<String, String> uploadExcelImageFile(@RequestParam("myFile1") CommonsMultipartFile myFile, Model model,
			String globalFileId, String globalCode) {
		boolean flag = false;// 声明上传文件成功与失败的标签
		Map<String, String> resultMap = new HashMap<String, String>();
		// 第一步:必须先做非空的判断
		if (!myFile.isEmpty()) {
			// 是获取要存储的文件夹路径
			String path = PropertiesUtil.getValue("fileStoreExcelImagePath") + "";
			File file = new File(path);
			// 建立文件夹包括路径
			if (!file.exists())
				file.mkdirs();
			// 获取上传文件格式
			String fileOldName = myFile.getOriginalFilename();// 文件原名
			resultMap.put("fileName", fileOldName);
			String format = fileOldName.substring(fileOldName.lastIndexOf("."));// 文件的格式
			// 文件新名(目的是防止文件名的重名的冲突)
			final String fileNewName = new Date().getTime() + format;
			resultMap.put("fileNewName", fileNewName);
			File file1 = new File(path + "/" + fileNewName);
			resultMap.put("fileNewPath",path+ "/" + fileNewName);
			try {
				// 将文件上传到此文件file1
				myFile.getFileItem().write(file1);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return resultMap;
	}

参考文章:

https://www.cnblogs.com/lin-bear/p/5193096.html
https://blog.youkuaiyun.com/u012814506/article/details/47783941

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值