文件上传
1、pom.xml追加
commons-fileupload
commons-io
commons-codec
2、dispatcherservlet-servlet.xml追加
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize" value="2000000" /> <property name="defaultEncoding" value="utf-8" /> </bean>
3、前端
$('#logo').ajaxSubmit({ type: "post", url: '/test', dataType: "json", success: function(resp) { alert(resp); } });
<form id="logo" class="hide" method="post" enctype="multipart/form-data"> <input name="file" type="file" /> <input name="imageKind" type="hidden" value="1" /> <button onclick="postFile()">click</button> </form>
4、文件在控制器用以下形式作为参数
@RequestParam("file") MultipartFile file
5、工具类
import java.io.File; import java.io.IOException; import org.apache.commons.codec.digest.DigestUtils; import org.springframework.web.multipart.MultipartFile; /** * 工具类:为MultipartFile,在转移和URI映射上,提供解决方案 * * @author Deolin */ public class FileUtil { private static String filename(MultipartFile file) { return file.getOriginalFilename(); } private static String extension(MultipartFile file) { String filename = filename(file); return filename.substring(filename.lastIndexOf(".") + 1); } private static String md5(MultipartFile file) throws IOException { return DigestUtils.md5Hex(file.getInputStream()); } private static String destFilename(MultipartFile file) throws IOException { return md5(file) + "." + extension(file); } /** * 将文件转移至[C:\\upload-image\],并以其MD5码作为文件名 * * @param originFile 原MultipartFile对象 * @throws IOException */ public static void transferFrom(MultipartFile originFile) throws IOException { File destFile = new File(BasicsConstant.FILE_UPLOAD_FLODER + destFilename(originFile)); if (!destFile.exists()) { originFile.transferTo(destFile); } } /** * 获取文件映射URI * * @param file MultipartFile对象 * @return String URI * @throws IOException */ public static String uri(MultipartFile file) throws IOException { return BasicsConstant.FILE_UPLOAD_URI + destFilename(file); } }
6、如果需要将文件保存至本地,而不是webapp目录下的话,
对于开发环境,需要在pom.xml的jetty-maven-plugin添加以下配置(示例)
<plugin> <groupId>org.mortbay.jetty</groupId> <artifactId>jetty-maven-plugin</artifactId> <configuration> <scanIntervalSeconds>2</scanIntervalSeconds> <webApp> <contextPath>/</contextPath> <defaultsDescriptor> src/main/resources/jetty/webdefault.xml </defaultsDescriptor> </webApp> <stopKey>shutdown</stopKey> <stopPort>8085</stopPort> <contextHandlers> <contextHandler implementation="org.eclipse.jetty.webapp.WebAppContext"> <contextPath>/image</contextPath> <resourceBase>C:\upload-image</resourceBase> </contextHandler> </contextHandlers> </configuration> </plugin>
对于部署环境,如tomcat,需要在%TOMCAT%\conf\server.xml的Host标签内添加以下标签
<Context docBase="C:\\upload-image" path="/image" reloadable="true"/>
※第6点出现的两个本地路径[c:\upload-image],需要在第5点的工具类中出现[BasicsConstant.FILE_UPLOAD_FLODER]。