springMVC-笔记006-文件的上传

来源:互联网 发布:性party知乎 编辑:程序博客网 时间:2024/06/16 20:35

配置文件:

<!-- 文件上传 --><bean id="multipartResolver"class="org.springframework.web.multipart.commons.CommonsMultipartResolver"><!-- 文件最大5M --><property name="maxUploadSize" value="5242880" /><!-- 默认编码UTF-8 --><property name="defaultEncoding" value="UTF-8" /><!-- 延迟加载 --><property name="resolveLazily" value="true" /></bean>

上传页面:

<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Insert title here</title></head><body><form action="${pageContext.request.contextPath}/doupload"method="post" enctype="multipart/form-data"><table><caption>文件上传</caption><tr><td><input name="file" type="file" /></td></tr><tr><td><input type="submit" value="上传" /></td></tr></table></form></body></html>

Controller:

package com.mvc.contorller;import java.io.File;import java.io.IOException;import java.util.Map;import org.apache.commons.io.FileUtils;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.multipart.MultipartFile;import com.mvc.util.UploadUtils;@Controllerpublic class FileuploadController {// 跳转文件上传页面@RequestMapping(value = "/upload", method = RequestMethod.GET)public String toUploadPage() {return "upload";}// 文件上传@RequestMapping(value = "/doupload", method = RequestMethod.POST)public String doUpload(@RequestParam("file") MultipartFile file, Map<String, Object> model) throws IOException {// 设置文件保存位置String uploadPath = "D:\\bbb\\apache-tomcat-7.0.70\\webapps\\uploadtest\\";// 设置文件保存名字String fileName = UploadUtils.getUUIDName(file.getOriginalFilename());if (!file.isEmpty()) {FileUtils.copyInputStreamToFile(file.getInputStream(), new File(uploadPath, fileName));}model.put("filename", fileName);return "uploadok";}}

工具类:

package com.mvc.util;import java.util.UUID;/** * 文件上传工具 *  * @author Administrator */public class UploadUtils {public static String getUUIDName(String filename) {// 查找int index = filename.lastIndexOf(".");// 截取String lastname = filename.substring(index, filename.length());String uuid = UUID.randomUUID().toString().replace("-", "");return uuid + lastname;}}

成功页面:

<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Insert title here</title></head><body><table><caption>上传成功</caption><tr><td><img src="/uploadtest/${filename}" /></td></tr></table></body></html>