标签:Apache,commons,fileupload,文件上传
文件上传的方法主要目前有两个常用的,一个是SmartUpload,一个是Apache的Commons fileupload.
我们这里主要介绍下第二个的用法,首先要上传文件,注意几个问题:
1 form表单内,要添加空间<input type="file" name="myfile">
2 form表单的内容格式要定义成multipart/form-data格式
3 需要类库:1 commons-io.jar 2commons-fileupload-1.3.1.jar
接下来我们看下用法。
首先阅读Apache commons fileupload的官方文档可以发现下面几个常用的函数:
1 创建文件解析对象
DiskFileUpload diskFileUpload = new DiskFileUpload();
2 进行文件解析后放在List中,因为这个类库支持多个文件上传,因此把结果会存在List中。
List<FileItem> list = diskFileUpload.parseRequest(request);
3 获取上传文件,进行分析(不是必须)
File remoteFile = new File(new String(fileItem.getName().getBytes(),"UTF-8"));
4 创建新对象,进行流拷贝
file1 = new File(this.getServletContext().getRealPath("attachment"),remoteFile.getName());
file1.getParentFile().mkdirs();
file1.createNewFile();
InputStream ins = fileItem.getInputStream();
OutputStream ous = new FileOutputStream(file1);
try{
byte[] buffer = new byte[1024];
int len = 0;
while((len = ins.read(buffer)) > -1)
ous.write(buffer,0,len);
out.println("以保存文件"+file1.getAbsolutePath()+"<br/>");
}finally{
ous.close();
ins.close();
}
这样我们就完成了文件的上传。
fileUpload.html
<form action="servlet/UploadServlet" method="post" enctype="multipart/form-data">
<div align="center">
<fieldset style="width:80%">
<legend>上传文件</legend><br/>
<div align="left">上传文件1</div>
<div align="left">
<input type="file" name="file1"/>
</div>
<div align="left">上传文件2</div>
<div align="left">
<input type="file" name="file2"/>
</div>
<div>
<div align='left'>上传文件说明1</div>
<div align='left'><input type="text" name="description1"/></div>
</div>
<div>
<div align='left'>上传文件说明2</div>
<div align='left'><input type="text" name="description2"/></div>
</div>
<div>
<div align='left'>
<input type='submit' value="上传文件"/>
</div>
</div>
</fieldset>
</div>
</form>
web.xml
<servlet>
<servlet-name>UploadServlet</servlet-name>
<servlet-class>com.test.hello.UploadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UploadServlet</servlet-name>
<url-pattern>/servlet/UploadServlet</url-pattern>
</servlet-mapping>
UploadServlet.java
package com.test.hello;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
public class UploadServlet extends HttpServlet {
/**
* Constructor of the object.
*/
public UploadServlet() {
super();
}
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setCharacterEncoding("UTF-8");
response.getWriter().println("请以POST方式上传文件");
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
@SuppressWarnings({ "unchecked", "deprecation" })
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
File file1 = null,file2=null;
String description1 = null,description2 = null;
response.setCharacterEncoding("UTF-8");
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
DiskFileUpload diskFileUpload = new DiskFileUpload();
try{
List<FileItem> list = diskFileUpload.parseRequest(request);
out.println("遍历所有的FileItem...<br/>");
for(FileItem fileItem : list){
if(fileItem.isFormField()){
if("description1".equals(fileItem.getFieldName())){
out.println("遍历到description1 ... <br/>");
description1 = new String(fileItem.getString().getBytes(),"UTF-8");
}
if("description2".equals(fileItem.getFieldName())){
out.println("遍历到description2 ... <br/>");
description2 = new String(fileItem.getString().getBytes(),"UTF-8");
}
}else{
if("file1".equals(fileItem.getFieldName())){
File remoteFile = new File(new String(fileItem.getName().getBytes(),"UTF-8"));
out.println("遍历到file1...<br/>");
out.println("客户端文件位置:"+remoteFile.getAbsolutePath()+"<br/>");
file1 = new File(this.getServletContext().getRealPath("attachment"),remoteFile.getName());
file1.getParentFile().mkdirs();
file1.createNewFile();
InputStream ins = fileItem.getInputStream();
OutputStream ous = new FileOutputStream(file1);
try{
byte[] buffer = new byte[1024];
int len = 0;
while((len = ins.read(buffer)) > -1)
ous.write(buffer,0,len);
out.println("以保存文件"+file1.getAbsolutePath()+"<br/>");
}finally{
ous.close();
ins.close();
}
}
if("file2".equals(fileItem.getFieldName())){
File remoteFile = new File(new String(fileItem.getName().getBytes(),"UTF-8"));
out.println("遍历到file2...<br/>");
out.println("客户端文件位置:"+remoteFile.getAbsolutePath()+"<br/>");
file2 = new File(this.getServletContext().getRealPath("attachment"),remoteFile.getName());
file2.getParentFile().mkdirs();
file2.createNewFile();
InputStream ins = fileItem.getInputStream();
OutputStream ous = new FileOutputStream(file2);
try{
byte[] buffer = new byte[1024];
int len = 0;
while((len = ins.read(buffer)) > -1)
ous.write(buffer,0,len);
out.println("以保存文件"+file2.getAbsolutePath()+"<br/>");
}finally{
ous.close();
ins.close();
}
}
}
out.println("Request 解析完毕<br/><br/>");
}
}catch(FileUploadException e){}
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println(" <BODY>");
if(file1 != null){
out.println("<div>");
out.println(" <div align='left'>file1;</div>");
out.println(" <div align='left'><a href='"+request.getContextPath()+"/attachment/"+
file1.getName()+"'target=_blank>"+file1.getName()+"</a>");
out.println("</div>");
out.println("</div>");
}
if(file2 != null){
out.println("<div>");
out.println(" <div align='left'>file2;</div>");
out.println(" <div align='left'><a href='"+request.getContextPath()+"/attachment/"+
file2.getName()+"'target=_blank>"+file2.getName()+"</a>");
out.println("</div>");
out.println("</div>");
}
out.println("<div>");
out.println(" <div align='left'>description1:</div>");
out.println(" <div align='left'>");
out.println(description1);
out.println("</div>");
out.println("</div>");
out.println("<div>");
out.println(" <div align='left'>description2:</div>");
out.println(" <div align='left'>");
out.println(description2);
out.println("</div>");
out.println("</div>");
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
}
/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}
}
运行示例


猜你喜欢
- 一、@ConditionalOnClass() Spring中存在指定class对象时,注入指定配置和ConditionalOnBean()
- java * 的方法总结AOP的拦截功能是由java中的 * 来实现的。说白了,就是在目标类的基础上增加切面逻辑,生成增强的目标类(该
- springboot集成RabbitMQ非常简单,如果只是简单的使用配置非常少,springboot提供了spring-boot-start
- 引言最近,因为开发的时候经改动依赖的库,所以,我想对 Gradle 脚本做一个调整,用来动态地将依赖替换为源码。这里以 android-mv
- 【前言】AOP(Aspect Orient Programming),我们一般称为面向方面(切面)编程,作为面向对象的一种补充,用于处理系统
- 一、Socket 基础知识1.1 Socket 概述Socket 指的是“插座”,是应用层与传输层之
- 创建项目在主界面的左侧菜单选 新建在向导中选择 输入项目名称,类型选择 构建一个自由风格的软件项目点确定进入项目的配置界面源码管理 选择gi
- 目录引言SqlSessionFactory不使用 XML 构建 SqlSessionFactorySqlSessionFactoryBuil
- 本文实例讲述了C#中foreach语句使用break暂停遍历的方法。分享给大家供大家参考。具体分析如下:下面的代码演示了在C#中使用fore
- java文件输出流是一种用于处理原始二进制数据的字节流类。为了将数据写入到文件中,必须将数据转换为字节,并保存到文件。package com
- 一.模拟问题最近在公司遇到一个问题,挂号系统是做的集群,比如启动了两个相同的服务,病人挂号的时候可能会出现同号的情况,比如两个病人挂出来的号
- 大致思路:注解实现方式:就是用 反射机制. 获取指定的包下使用了注解的类,存储在一个map容器, 然后获取map容器下类的属性, 利用反射给
- 分页是Java Web项目常用的功能,昨天在Spring MVC中实现了简单的分页操作和搜索分页,在此记录一下。使用的框架为(MyBatis
- like模糊查询特殊字符报错转义处理方案1 <if test="projectName!
- private void button1_Click(object sender, EventArgs e) {
- Android在自定义控件时,经常需要获得屏幕的宽高,每次都要写,不妨直接把他封装成工具类,直接拿来用,废话不说,直接上代码/** * &n
- 本文实例讲述了java针对电话号码正则匹配的方法。分享给大家供大家参考。具体如下:public interface RegExpConst
- 常用的对数组进行的操作1、求数组中最大值,最小值思路:假设下标为0的元素是最大值,遍历数组,依次跟max进行比较,如果有元素比这个max还大
- 本文实例为大家分享了openoffice+jodconverter-code-3.0-bate4实现ppt转图片的具体代码,供大家参考,具体
- 实现“摇一摇”功能,其实很简单,就是检测手机的重力感应,具体实现代码如下:1、在 AndroidManifest.xml 中添加操作权限2、