SpringMvc MultipartFile 图片文件上传

spring-servlet.xml

1 <!-- SpringMVC上传文件时,需要配置MultipartResolver处理器 -->
2 <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
3 <property name="defaultEncoding" value="UTF-8" />
4 <!-- 指定所上传文件的总大小,单位字节。注意maxUploadSize属性的限制不是针对单个文件,而是所有文件的容量之和 -->
5 <property name="maxUploadSize" value="10240000" />
6 </bean>

 upload/index.jsp

 1 <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
 2 <!DOCTYPE HTML>
 3 <html>
 4 	<head>
 5 		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 6 		<title>单图片上传</title>
 7 	</head>
 8 	<body>
 9 		<fieldset>
10 			<legend>图片上传</legend>
11 			<h2>只能上传单张10M以下的 PNG、JPG、GIF 格式的图片</h2>
12 			<form action="/shop/auth/photoUpload" method="post" enctype="multipart/form-data">
13 				选择文件:<input type="file" name="file">
14 				<input type="submit" value="上传">
15 			</form>
16 		</fieldset>
17 	</body>
18 </html>

 

或者使用ExtJs

js/user/photoUpload.js

 1 Ext.onReady(function(){
 2 	Ext.create('Ext.form.Panel', {
 3 	title: '图片上传',
 4 	width: 600,
 5 	bodyPadding: 10,
 6 	frame: true,
 7  	renderTo: Ext.getBody(),
 8  		items: [{
 9			xtype: 'filefield',
10 			name: 'file',
11 			fieldLabel: 'Photo',
12 			labelWidth: 50,
13 			msgTarget: 'side',
14 			fileUpload: true ,
15 			allowBlank: false,
16			blankText:"Select an image",
17 			emptyText: 'You can only upload a single PNG 10M or less, JPG, GIF format images',
18 			anchor: '100%',
19 			buttonText: '选择图片'
20  		}],
21
22  	buttons: [{
23 		text: '上传',
24 		handler: function() {
25 			var form = this.up('form').getForm();
26 			if(form.isValid()){
27  				form.submit({
28 					url: '/shop/auth/photoUpload',
29 					waitMsg: '正在上传图片...',
30 					success: function(fp, o) {
31 						Ext.Msg.alert('提示', o.result.msg);
32  					}
33  			});
34  		}
35  	}
36  }]
37  });
38 });

pages/user/photoUpload.html

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4 <meta charset="UTF-8">
 5 <title>图片上传</title>
 6 </head>
 7 <link href="../../ext-4.2.1.883/resources/css/ext-all.css" rel="stylesheet"
 8  type="text/css" />
 9 <script type="text/javascript" src="../../ext-4.2.1.883/ext-all.js"></script>
10 <script src="../../js/user/photoUpload.js" type="text/javascript"></script>
11 <body>
12
13 </body>
14 </html>  

AuthController.java

/**
* 图片文件上传
*/
@ResponseBody
@RequestMapping(value = "/photoUpload", method = RequestMethod.POST)
public ResultData<Object> photoUpload(MultipartFile file, HttpServletRequest request, HttpServletResponse response, HttpSession session) throws IllegalStateException, IOException {
ResultData<Object> resultData = new ResultData<>();
// 判断用户是否登录
/*User user=(User) session.getAttribute("user");
if (user==null) {
resultData.setCode(40029);
resultData.setMsg("用户未登录");
return resultData;
}*/
if (file != null) {// 判断上传的文件是否为空
String path = null;// 文件路径
String type = null;// 文件类型
String fileName = file.getOriginalFilename();// 文件原名称
System.out.println("上传的文件原名称:" + fileName); // 判断文件类型
type = fileName.indexOf(".") != -1 ? fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()) : null;
if (type != null) {// 判断文件类型是否为空
if ("GIF".equals(type.toUpperCase()) || "PNG".equals(type.toUpperCase()) || "JPG".equals(type.toUpperCase())) { // 项目在容器中实际发布运行的根路径
String realPath = request.getSession().getServletContext().getRealPath("/"); // 自定义的文件名称
String trueFileName = String.valueOf(System.currentTimeMillis()) + fileName; // 设置存放图片文件的路径
path = realPath +/*System.getProperty("file.separator")+*/trueFileName;
System.out.println("存放图片文件的路径:" + path); // 转存文件到指定的路径
file.transferTo(new File(path));
System.out.println("文件成功上传到指定目录下");
} else {
System.out.println("不是我们想要的文件类型,请按要求重新上传");
return null;
}
} else {
System.out.println("文件类型为空");
return null;
}
} else {
System.out.println("没有找到相对应的文件");
return null;
}
return resultData;
}

 ResultData.java 代码如下:

public class ResultData<T> {

private T data;

private int code = 200;

private String msg;

private Boolean success = true;

public Boolean getSuccess() {
return success;
}

public void setSuccess(Boolean success) {
this.success = success;
}

public T getData() {
return data;
}

public void setData(T data) {
this.data = data;
}

public int getCode() {

return code;
}

public void setCode(int code) {
if (200 != code) {
success = false;
}
this.code = code;
}

public String getMsg() {
return msg;
}

public void setMsg(String msg) {
this.msg = msg;
}

}
posted @ 2016-04-24 14:43  LEARN4J  阅读(102941)  评论(8编辑  收藏  举报