设为首页 收藏本站
查看: 867|回复: 0

[经验分享] 文件上传之Apache commons fileupload使用

[复制链接]

尚未签到

发表于 2015-8-1 06:55:22 | 显示全部楼层 |阅读模式
    文件上传的方法主要目前有两个常用的,一个是SmartUpload,一个是Apache的Commons fileupload.
    我们这里主要介绍下第二个的用法,首先要上传文件,注意几个问题:
    1 form表单内,要添加空间
    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 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()+"");
}finally{
ous.close();
ins.close();
}
    这样我们就完成了文件的上传。

fileUpload.html






上传文件
上传文件1



上传文件2




上传文件说明1



上传文件说明2










web.xml




UploadServlet
com.test.hello.UploadServlet


UploadServlet
/servlet/UploadServlet

UploadServlet.java


DSC0000.gif DSC0001.gif


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.
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
    }
/**
* The doGet method of the servlet.
*
* 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.
*
* 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 list = diskFileUpload.parseRequest(request);
out.println("遍历所有的FileItem...");
for(FileItem fileItem : list){
if(fileItem.isFormField()){
if("description1".equals(fileItem.getFieldName())){
out.println("遍历到description1 ... ");
description1 = new String(fileItem.getString().getBytes(),"UTF-8");
}
if("description2".equals(fileItem.getFieldName())){
out.println("遍历到description2 ... ");
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...");
out.println("客户端文件位置:"+remoteFile.getAbsolutePath()+"");
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()+"");
}finally{
ous.close();
ins.close();
}
}
if("file2".equals(fileItem.getFieldName())){
File remoteFile = new File(new String(fileItem.getName().getBytes(),"UTF-8"));
out.println("遍历到file2...");
out.println("客户端文件位置:"+remoteFile.getAbsolutePath()+"");
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()+"");
}finally{
ous.close();
ins.close();
}
}
}
out.println("Request 解析完毕");
}
}catch(FileUploadException e){}
out.println("");
out.println("");
out.println("  A Servlet");
out.println("  ");
if(file1 != null){
out.println("");
out.println(" file1;");
out.println(" "+file1.getName()+"");
out.println("");
out.println("");
}
if(file2 != null){
out.println("");
out.println(" file2;");
out.println(" "+file2.getName()+"");
out.println("");
out.println("");
}
out.println("");
out.println(" description1:");
out.println(" ");
out.println(description1);
out.println("");
out.println("");
out.println("");
out.println(" description2:");
out.println(" ");
out.println(description2);
out.println("");
out.println("");
out.println("  ");
out.println("");
out.flush();
out.close();
}
/**
* Initialization of the servlet.
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
    }
}
View Code
运行示例
DSC0002.png
DSC0003.png

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-92805-1-1.html 上篇帖子: java中ant包中的org.apache.tools.zip实现压缩和解压缩 下篇帖子: Apache Mina 源码分析。
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表