您的位置:首页 > 编程语言 > Java开发

Spring mvc JS上传文件

2015-09-28 09:57 585 查看
在Spring mvc xml 中添加

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 指定所上传文件的总大小不能超过800KB......注意maxUploadSize属性的限制不是针对单个文件,而是所有文件的容量之和 -->
<property name="maxUploadSize" value="500000"/>
</bean>

<bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<!-- 遇到MaxUploadSizeExceededException异常时,跳转到/page/html/errorGolbal.html页面 -->
<prop key="org.springframework.web.multipart.MaxUploadSizeExceededException">/page/errorGolbal</prop>
</props>
</property>
</bean>


上传图片代码

@ResponseBody
@RequestMapping("/fileUpload")
public String fileUpload( @RequestParam MultipartFile[] myfiles, HttpServletRequest request, HttpServletResponse response) throws Exception{
String realPath = request.getSession().getServletContext().getRealPath("/upload/article");
response.setContentType("text/plain; charset=UTF-8");
PrintWriter out = response.getWriter();
long fileSize = 0;
int height = 0;
int width = 0;
String fileName = null;
String path = null;
for(MultipartFile myfile : myfiles){
if(myfile.isEmpty()){
out.print("{\"message\":\"请选择图片再次上传!!\",\"status\":-1}");
out.flush();
return null;
}else{
try {
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
fileSize = myfile.getSize(); //图片大小
String str = myfile.getOriginalFilename();
String suffix = str.substring(str.indexOf("."));
String name = str.substring(0, str.indexOf("."));
fileName = MD5Util.md5Encode(df.format(new Date()))+suffix; //名称
FileUtils.copyInputStreamToFile(myfile.getInputStream(), new File(realPath, fileName));
} catch (Exception e) {
out.print("{\"message\":\"上传失败\",\"status\":-1}");
out.flush();
return null;
}
}
}

path = request.getContextPath() + "/upload/article/" + fileName; //url路径
String filepath = request.getContextPath() + "/upload/article/";
BufferedImage bufferedImage = ImageIO.read(new File(realPath+'/'+fileName));
width = bufferedImage.getWidth(); //宽度
height = bufferedImage.getHeight(); //高度

out.print("{\"data\":{\"path\":\""+path+"\",\"size\":\""+fileSize+"\",\"width\":\""+width+"\",\"height\":\""+height+"\",\"fileName\":\""+fileName+"\",\"filepath\":\""+filepath+"\"},\"status\":1}");
out.flush();
return null;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java