这个博客其实去年八九月份就开始写了,当时一直比较忙,很多东西都没有整理,所以一直在我的草稿箱里。
之前在使用ueditor的时候就涉及到写后台上传文件的类,当时多多少少也接触过很多文件上传的方法,今天特意整理备忘一下。
一,Apache的common fileupload
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.2.2</version>
</dependency>
我这里有个简单实现,前台是一个html做一个form提交,提交的地址是servlet,servlet来处理上传文件的逻辑。并输出成功的内容
前台html展示,注意form的enctype必须是mutipart/form-data
<form name="myform" action="/fileUploadServlet" method="post"
enctype="multipart/form-data">
Your name: <br>
<input type="text" name="name" size="15"><br>
File:<br>
<input type="file" name="myfile"><br>
<br>
<input type="submit" name="submit" value="Commit">
</form>
后台servlet处理
try {
String uploadFilePath="d:\\temp";
File uploadFile=new File(uploadFilePath);
if (!uploadFile.exists()) {
uploadFile.mkdirs();
}
File tempPathFile = new File("d:\\temp\\buffer\\");
if (!tempPathFile.exists()) {
tempPathFile.mkdirs();
}
PrintWriter out = resp.getWriter();
boolean isMultipart = ServletFileUpload.isMultipartContent(request);//检查输入请求是否为multipart表单数据。
if (isMultipart == true) {
DiskFileItemFactory factory = new DiskFileItemFactory();//为该请求创建一个DiskFileItemFactory对象,通过它来解析请求。执行解析后,所有的表单项目都保存在一个List中。
//设置缓冲区
factory.setSizeThreshold(4096); // 设置缓冲区大小,这里是4kb
factory.setRepository(tempPathFile);//设置缓冲区目录
ServletFileUpload upload = new ServletFileUpload(factory);
//设置文件大小
upload.setSizeMax(4194304);
List<FileItem> items = upload.parseRequest(request);
Iterator<FileItem> itr = items.iterator();
while (itr.hasNext()) {
FileItem item = (FileItem) itr.next();
//检查当前项目是普通表单项目还是上传文件。
if (item.isFormField()) {//如果是普通表单项目,显示表单内容。
String fieldName = item.getFieldName();
if (fieldName.equals("name")) //对应demo1.html中type="text" name="name"
out.println("the field name is" + item.getString());//显示表单内容。
} else {//如果是上传文件,显示文件名。
out.println("the upload file name is" + item.getName());
String fileName=item.getName();//获得文件名,包括路径
if(fileName!=null){
File fullFile=new File(item.getName());
File savedFile=new File(uploadFilePath,fullFile.getName());
item.write(savedFile);
out.println("upload succeed");
}
}
}
} else {
out.print("the enctype must be multipart/form-data");
}
} catch (Exception e) {
e.printStackTrace();
}
参考文档:
http://zhangjunhd.blog.51cto.com/113473/18331
http://www.blogjava.net/sitinspring/archive/2008/04/12/192408.html
二,使用JSP smartupload
smartUpload的使用很简单,下面是一个demo
private ServletConfig config;
final public void init(ServletConfig config) throws ServletException {
this.config = config;
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
try {
PrintWriter out = response.getWriter();
// 变量定义
int count = 0;
SmartUpload mySmartUpload = new SmartUpload();
mySmartUpload.initialize(config, request, response);
mySmartUpload.upload();
for (int i = 0; i < mySmartUpload.getFiles().getCount(); i++) {
com.jspsmart.upload.File myfile = mySmartUpload.getFiles().getFile(i);
String fileName = myfile.getFileName();
count = mySmartUpload.save("d://temp//upload");
}
out.println(count + " file uploaded.");
} catch (Exception e) {
e.printStackTrace();
}
}
private ServletConfig config;
final public void init(ServletConfig config) throws ServletException {
this.config = config;
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
try {
String temp_p =request.getParameter("downloadFileName");
byte[] temp_t=temp_p.getBytes("ISO8859_1");
String fileName=new String(temp_t,"GBK");
SmartUpload mySmartUpload = new SmartUpload();
try {
mySmartUpload.initialize(config, request, response);
mySmartUpload.setContentDisposition(null);
mySmartUpload.downloadFile("d://temp//upload//"+fileName);
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
这里面注意一下:
下载文件的方法中,public void setContentDisposition(String contentDisposition)
其中,contentDisposition为要添加的数据。如果contentDisposition为null,则组件将自动添加"attachment;",以表明将下载的文件作为附件,结果是IE浏览器将会提示另存文件,而不是自动打开这个文件(IE浏览器一般根据下载的文件扩展名决定执行什么操作,扩展名为doc的将用Word程序打开,扩展名为pdf的将用acrobat程序打开,等等)。
上传文件的方法中,public int save(String destPathName,int option)
其中,destPathName为文件保存目录,option为保存选项,它有三个值,分别是SAVE_PHYSICAL,SAVE_VIRTUAL和SAVE_AUTO。(同File类的saveAs方法的选项之值类似)SAVE_PHYSICAL指示组件将文件保存到以操作系统根目录为文件根目录的目录下,SAVE_VIRTUAL指示组件将文件保存到以Web应用程序根目录为文件根目录的目录下,而SAVE_AUTO则表示由组件自动选择。
http://www.knowsky.com/3136.html
http://www.blogjava.net/hijackwust/archive/2007/08/22/138598.html
三,使用springmvc的uplaod
这里首先要搭建springmvc的环境
web.xml配置如下:
<!--spring mvc 配置 start-->
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--spring mvc 配置 end-->
其中servlet-name会自动去找spring-servlet.xml,同时创建一个文件叫applicationContext.xml
其中spring-servlet.xml的配置如下:
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize">
<value>104857600</value>
</property>
<property name="maxInMemorySize">
<value>4096</value>
</property>
</bean>
<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="/springmvcupload.do">uploadController</prop>
</props>
</property>
</bean>
<bean id="uploadController" class="com.xiaoming.test.springupload.FileUploadController">
<property name="commandClass">
<value>com.xiaoming.test.springupload.FileUploadBean</value>
</property>
</bean>
其中java文件如下:
public class FileUploadBean {
private byte[] file;
public void setFile(byte[] file) {
this.file = file;
}
public byte[] getFile() {
return file;
}
}
public class FileUploadController extends SimpleFormController {
protected ModelAndView onSubmit(HttpServletRequest request,
HttpServletResponse response, Object cmd, BindException errors)
throws Exception {
FileUploadBean bean = (FileUploadBean) cmd;
byte[] bytes = bean.getFile();
//cast to multipart file so we can get additional information
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest.getFile("file");
String uploadDir = "D://temp";
File dirPath = new File(uploadDir);
if (!dirPath.exists()) {
dirPath.mkdirs();
}
String sep = System.getProperty("file.separator");
File uploadedFile = new File(uploadDir + sep+ file.getOriginalFilename());
FileCopyUtils.copy(bytes, uploadedFile);
System.out.println(uploadedFile.getAbsolutePath());
return new ModelAndView("/springupload/success.jsp");
}
protected void initBinder(HttpServletRequest request,
ServletRequestDataBinder binder) throws ServletException {
binder.registerCustomEditor(byte[].class,
new ByteArrayMultipartFileEditor());
}
}
参考文档:
http://laixi.kehui.net:82/index.php?op=article&file=read&aid=54812
http://www.iteye.com/topic/51272
总结一下,文件上传到的方法有很多,这里只是几种简单的实现方法。