Spring实现文件上传(示例代码)
在实际开发中,经常遇到要实现文件上传到服务器端的功能。spring可以继承commons-fileupload插件来实现文件上传的功能。分为前端jsp编写和后台controller的编写。
前期准备工作,首先要引入commons-fileupload这个jar包,pom.xml中的配置如下:
<!-- 实现文件上传,spring集成了这个功能 -->
<dependency>
<groupid>commons-fileupload</groupid>
<artifactid>commons-fileupload</artifactid>
<version>1.2.2</version>
</dependency>
然后配置拦截器,在dispatcher-servlet.xml中添加
<!-- 实现文件上传,这样一旦某个request是一个multipartrequest,它就会首先被multipartresolver处理,然后再转发相应的controller -->
<bean id="multipartresolver"
class="org.springframework.web.multipart.commons.commonsmultipartresolver">
<!-- 设置上传文件的最大尺寸为1mb -->
<property name="maxuploadsize">
<value>1048576</value>
</property>
</bean>
直接上代码:
1、前端jsp编写
upload.jsp
<%@ page language="java" pageencoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!doctype html public "-//w3c//dtd html 4.01 transitional//en">
<html>
<head>
<script src="resources/js/jquery.js"></script>
</head>
<body>
<form method="post" action="upload.do" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit" />
</form>
</body>
</html>
2、后台uploadcontroller编写
package nju.software.xkxt.web.controller;
import java.io.fileoutputstream;
import java.io.ioexception;
import java.io.inputstream;
import javax.servlet.http.httpservletrequest;
import javax.servlet.http.httpservletresponse;
import org.springframework.stereotype.controller;
import org.springframework.ui.modelmap;
import org.springframework.web.bind.annotation.requestmapping;
import org.springframework.web.bind.annotation.requestmethod;
import org.springframework.web.multipart.multipartfile;
import org.springframework.web.multipart.multiparthttpservletrequest;
/**
* @author typ
*
*/
@controller
public class uploadcontroller {
/**
* 进入下载界面
*
* @param request
* @param response
* @param model
* @return
* @throws ioexception
*/
@requestmapping(value = "upload_enter.do", method = requestmethod.get)
public string enter(httpservletrequest request,
httpservletresponse response, modelmap model) throws ioexception {
// 进入下载界面
return "upload";
}
/**
* 具体的实现下载功能
*
* @param request
* @param response
* @param model
* @throws ioexception
*/
@requestmapping(value = "upload.do", method = requestmethod.post)
public void upload(httpservletrequest request,
httpservletresponse response, modelmap model) throws ioexception {
multiparthttpservletrequest multipartrequest = (multiparthttpservletrequest) request;
// 得到上传的文件
multipartfile mfile = multipartrequest.getfile("file");
// 得到上传服务器的路径
string path = request.getsession().getservletcontext()
.getrealpath("/web-inf/upload/");
// 得到上传的文件的文件名
string filename = mfile.getoriginalfilename();
inputstream inputstream = mfile.getinputstream();
byte[] b = new byte[1048576];
int length = inputstream.read(b);
path += "\\" + filename;
// 文件流写到服务器端
fileoutputstream outputstream = new fileoutputstream(path);
outputstream.write(b, 0, length);
inputstream.close();
outputstream.close();
}
}
这样就很容易的实现了文件上传的功能。