commons-fileupload.jar实现文件上传
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>File upload</title>
</head>
<body>
//必须是multipart的表单数据。
<form name="myform" action="demo1.jsp" 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>
</body>
</html>
|
<%@ page language="java" contentType="text/html; charset=GB18030"
pageEncoding="GB18030"%>
<%@ page import="org.apache.commons.fileupload.*"%>
<%@ page import="org.apache.commons.fileupload.servlet.*"%>
<%@ page import="org.apache.commons.fileupload.disk.*"%>
<%@ page import="java.util.*"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<%
boolean isMultipart = ServletFileUpload.isMultipartContent(request);//检查输入请求是否为multipart表单数据。
if (isMultipart == true) {
FileItemFactory factory = new DiskFileItemFactory();//为该请求创建一个DiskFileItemFactory对象,通过它来解析请求。执行解析后,所有的表单项目都保存在一个List中。
ServletFileUpload upload = new ServletFileUpload(factory);
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.print("the field name is" + item.getString());//显示表单内容。
out.print("<br>");
} else {//如果是上传文件,显示文件名。
out.print("the upload file name is" + item.getName());
out.print("<br>");
}
}
} else {
out.print("the enctype must be multipart/form-data");
}
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>File upload</title>
</head>
<body>
</body>
</html>
|
the field name isjeff the upload file name isD:\C语言考试样题\作业题.rar |
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>File upload</title>
</head>
<body>
<form name="myform" action="demo2.jsp" method="post"
enctype="multipart/form-data">
File1:<br>
<input type="file" name="myfile"><br>
File2:<br>
<input type="file" name="myfile"><br>
<br>
<input type="submit" name="submit" value="Commit">
</form>
</body>
</html>
|
<%@ page language="java" contentType="text/html; charset=GB18030"
pageEncoding="GB18030"%>
<%@ page import="org.apache.commons.fileupload.*"%>
<%@ page import="org.apache.commons.fileupload.servlet.*"%>
<%@ page import="org.apache.commons.fileupload.disk.*"%>
<%@ page import="java.util.*"%>
<%@ page import="java.io.*"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<%String uploadPath="D:\\temp";
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if(isMultipart==true){
try{
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List<FileItem> items = upload.parseRequest(request);//得到所有的文件
Iterator<FileItem> itr = items.iterator();
while(itr.hasNext()){//依次处理每个文件
FileItem item=(FileItem)itr.next();
String fileName=item.getName();//获得文件名,包括路径
if(fileName!=null){
File fullFile=new File(item.getName());
File savedFile=new File(uploadPath,fullFile.getName());
item.write(savedFile);
}
}
out.print("upload succeed");
}
catch(Exception e){
e.printStackTrace();
}
}
else{
out.println("the enctype must be multipart/form-data");
}
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>File upload</title>
</head>
<body>
</body>
</html>
|
upload succeed |
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>File upload</title>
</head>
<body>
<form name="myform" action="demo3.jsp" method="post"
enctype="multipart/form-data">
File:<br>
<input type="file" name="myfile"><br>
<br>
<input type="submit" name="submit" value="Commit">
</form>
</body>
</html>
|
<%@ page language="java" contentType="text/html; charset=GB18030"
pageEncoding="GB18030"%>
<%@ page import="org.apache.commons.fileupload.*"%>
<%@ page import="org.apache.commons.fileupload.servlet.*"%>
<%@ page import="org.apache.commons.fileupload.disk.*"%>
<%@ page import="java.util.*"%>
<%@ page import="java.io.*"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<%
File uploadPath = new File("D:\\temp");//上传文件目录
if (!uploadPath.exists()) {
uploadPath.mkdirs();
}
// 临时文件目录
File tempPathFile = new File("d:\\temp\\buffer\\");
if (!tempPathFile.exists()) {
tempPathFile.mkdirs();
}
try {
// Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory();
// Set factory constraints
factory.setSizeThreshold(4096); // 设置缓冲区大小,这里是4kb
factory.setRepository(tempPathFile);//设置缓冲区目录
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// Set overall request size constraint
upload.setSizeMax(4194304); // 设置最大文件尺寸,这里是4MB
List<FileItem> items = upload.parseRequest(request);//得到所有的文件
Iterator<FileItem> i = items.iterator();
while (i.hasNext()) {
FileItem fi = (FileItem) i.next();
String fileName = fi.getName();
if (fileName != null) {
File fullFile = new File(fi.getName());
File savedFile = new File(uploadPath, fullFile
.getName());
fi.write(savedFile);
}
}
out.print("upload succeed");
} catch (Exception e) {
e.printStackTrace();
}
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>File upload</title>
</head>
<body>
</body>
</html>
|
package com.zj.sample;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
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.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
@SuppressWarnings("serial")
publicclass Upload extends HttpServlet {
private String uploadPath = "D:\\temp"; // 上传文件的目录
private String tempPath = "d:\\temp\\buffer\\"; // 临时文件目录
File tempPathFile;
@SuppressWarnings("unchecked")
publicvoid doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
try {
// Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory();
// Set factory constraints
factory.setSizeThreshold(4096); // 设置缓冲区大小,这里是4kb
factory.setRepository(tempPathFile);// 设置缓冲区目录
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// Set overall request size constraint
upload.setSizeMax(4194304); // 设置最大文件尺寸,这里是4MB
List<FileItem> items = upload.parseRequest(request);// 得到所有的文件
Iterator<FileItem> i = items.iterator();
while (i.hasNext()) {
FileItem fi = (FileItem) i.next();
String fileName = fi.getName();
if (fileName != null) {
File fullFile = new File(fi.getName());
File savedFile = new File(uploadPath, fullFile.getName());
fi.write(savedFile);
}
}
System.out.print("upload succeed");
} catch (Exception e) {
// 可以跳转出错页面
e.printStackTrace();
}
}
publicvoid init() throws ServletException {
File uploadFile = new File(uploadPath);
if (!uploadFile.exists()) {
uploadFile.mkdirs();
}
File tempPathFile = new File(tempPath);
if (!tempPathFile.exists()) {
tempPathFile.mkdirs();
}
}
}
|
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>File upload</title>
</head>
<body>
// action="fileupload"对应web.xml中<servlet-mapping>中<url-pattern>的设置.
<form name="myform" action="fileupload" method="post"
enctype="multipart/form-data">
File:<br>
<input type="file" name="myfile"><br>
<br>
<input type="submit" name="submit" value="Commit">
</form>
</body>
</html>
|
<servlet>
<servlet-name>Upload</servlet-name>
<servlet-class>com.zj.sample.Upload</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Upload</servlet-name>
<url-pattern>/fileupload</url-pattern>
</servlet-mapping>
|
本文出自 “子 孑” 博客,请务必保留此出处http://zhangjunhd.blog.51cto.com/113473/18331
自己根据上面包装了一下 ,把文件上传放入一个FileUpload类的静态方法upload中,方法的形式参数则为HttpServletRequest request和String uploadPath(上传到服务器的路径)
代码如下:
1、FileUpload类
- /*
- * FileUpload
- * @Author TGM
- */
- package com.FileUpload;
- import java.io.File;
- import java.util.Iterator;
- import java.util.List;
- import java.util.logging.Level;
- import java.util.logging.Logger;
- import javax.servlet.http.HttpServletRequest;
- import org.apache.commons.fileupload.FileItem;
- import org.apache.commons.fileupload.FileItemFactory;
- import org.apache.commons.fileupload.FileUploadException;
- import org.apache.commons.fileupload.disk.DiskFileItemFactory;
- import org.apache.commons.fileupload.servlet.ServletFileUpload;
- /**
- *
- * @author TGM
- */
- public class FileUpload {
- /**
- * 静态上传方法
- * @param request HttpServletRequest
- * @param uploadPath String 上传到服务器的文件存放路径
- * @return true 上传成功 false 上传失败
- */
- public static boolean upload(HttpServletRequest request, String uploadPath) {
- boolean isMultipart = ServletFileUpload.isMultipartContent(request);//检查输入请求是否为multipart表单数据。
- boolean flag = false;
- if (isMultipart == true) {
- FileItemFactory factory = new DiskFileItemFactory();//为该请求创建一个DiskFileItemFactory对象,通过它来解析请求。执行解析后,所有的表单项目都保存在一个List中。
- ServletFileUpload upload = new ServletFileUpload(factory);
- List<FileItem> items = null;
- try {
- items = upload.parseRequest(request);
- } catch (FileUploadException ex) {
- Logger.getLogger(FileUpload.class.getName()).log(Level.SEVERE, null, ex);
- }
- 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"
- System.out.print("the field name is" + item.getString() + "\n");//显示表单内容。
- }
- } else {//如果是上传文件,显示文件名。
- File fullFile = new File(item.getName());
- File savedFile = new File(uploadPath, fullFile.getName());
- try {
- item.write(savedFile);
- } catch (Exception ex) {
- Logger.getLogger(FileUpload.class.getName()).log(Level.SEVERE, null, ex);
- }
- flag = true;
- System.out.print("the upload file name is" + item.getName() + "\n");
- }
- }
- } else {
- System.out.print("the enctype must be multipart/form-data");
- }
- return flag;
- }
- }
2、index.html(上传表单)
- <!--
- To change this template, choose Tools | Templates
- and open the template in the editor.
- -->
- <!DOCTYPE html>
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=GB18030">
- <title>File upload</title>
- </head>
- <body>
- <form name="myform" action="doUpload2.jsp" method="post"
- enctype="multipart/form-data">
- Your name: <br>
- <input type="text" name="name" size="15"><br>
- File2:<br>
- <input type="file" name="myfile1"><br>
- File2:<br>
- <input type="file" name="myfile2"><br>
- <br>
- <input type="submit" name="submit" value="Commit">
- </form>
- </body>
- </html>
3、doUpload2.jsp 接收处理页面
- <%--
- Document : doUpload2
- Created on : 2012-9-6, 19:24:20
- Author : TGM
- --%>
- <%@page import="com.FileUpload.FileUpload"%>
- <%@page contentType="text/html" pageEncoding="UTF-8"%>
- <!DOCTYPE html>
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
- <title>JSP Page</title>
- </head>
- <body>
- <%
- boolean isUp = FileUpload.upload(request, "D:\\");
- if(isUp){
- out.write("上传成功!");
- } else {
- out.write("上传失败!");
- }
- %>
- </body>
- </html>
commons-fileupload.jar实现文件上传的更多相关文章
- 【转】commons-fileupload-1.2.1.jar和commons-io-1.3.2.jar实现文件上传
总共:一个upload.jsp,一个FileUploadServlet.java,两个文件:ImagesUploaded,ImagesUploadTemp, 一个web.xml,两个架包:common ...
- dwz+jquery+fileupload+springmvc实现文件上传 及图片预览
1 前台jsp:文件的上传利用了iframe实现局部刷新功能.使用了apache的fileupload组件,用到的jar: commons-fileupload.jar,commons-io.jarD ...
- 模拟文件上传(二):使用apache fileupload组件进行文件上传
其中涉及到的jar包: jsp显示层: <%@ page language="java" import="java.util.*" pageEncodin ...
- 框架中如何根据fileupload工具包实现文件上传功能
工具包 Apache-fileupload.jar – 文件上传核心包. Apache-commons-io.jar – 这个包是fileupload的依赖包.同时又是一个工具包. 代码 servle ...
- FileUpload框架实现文件上传(多个文件)和下载
一.文件上传: 对于大文件执行下面的代码之间卡死 package com.example.web.service.servlet; import java.io.File; import java.i ...
- asp.net+bootstrap上传图片+FileUpload控件文件上传下载
ps:我数据库使用的pgsql,看个人修改. 代码asp.net 的,使用了mootools框架,里面包含了bootstrap上传图片,查看预览,还加了个上传任意文件的FileUpload.(界面随便 ...
- Java 利用Apache Commons Net 实现 FTP文件上传下载
package woxingwosu; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import ...
- SpringMVC中使用CommonsMultipartResolver进行文件上传
概述: CommonsMultipartResolver是基于Apache的Commons FileUpload来实现文件上传功能的.所以在项目中需要相应的jar文件. FileUpload版本要求1 ...
- ajax异步文件上传,iframe方式
不是我写的,我看了他的,思路很明确: 实现思路: 在js脚本中动态创建form,动态创建form中的内容,将文件上传的内容以隐藏域的方式提交过去,然后写好回调等. 感觉思路不难,但是我写不出来,感觉需 ...
随机推荐
- memcache+magent的高可用
memcache+magent的高可用 一.安装步骤: 1.编译安装libevent: wget http://monkey.org/~provos/libevent-1.4.9-stable.tar ...
- 004.测试解析php,安装discuz
一.配置解析php 编辑nginx配置文件/usr/local/nginx/conf/nginx.conf [root@huh ~]# vim /usr/local/nginx/conf/nginx. ...
- js的encodeURIComponent与java的URLEncoder的区别
js中的encodeURIComponent这个函数和java中的URLEncoder有少数不一样的.如下表格就是区别 ascii java js + %20 ! %21 ! ' %27 ' ( ...
- ipv4理论知识2-分类编址、ip分类、网络标识、主机标识、地址类、地址块
分类编址 ipv4的体系结构中有分类编址和无分类编址(后续会介绍到),在分类编址时,ipv4地址分为A.B.C.D.E这5类.每类占用的IP比例和个数如下图: ipv4分类识别 计算机以二进制方式存储 ...
- execve(file, argv, env)参数argv获取字符串个数
/* Copyright (C) 1999, 2000, 2002, 2003 Free Software Foundation, Inc. This file is part of the GNU ...
- AC日记——挤牛奶 洛谷 P1204
题目描述 三个农民每天清晨5点起床,然后去牛棚给3头牛挤奶.第一个农民在300秒(从5点开始计时)给他的牛挤奶,一直到1000秒.第二个农民在700秒开始,在 1200秒结束.第三个农民在1500秒开 ...
- python 类属性与方法
Python 类属性与方法 标签(空格分隔): Python Python的访问限制 Python支持面向对象,其对属性的权限控制通过属性名来实现,如果一个属性有双下划线开头(__),该属性就无法被外 ...
- php-设置关键词高亮的字符串处理函数
/** * 设置关键词高亮的字符串处理函数 * @param [string] $str [要高亮的字符串] * @param array $word_arr [关键词] */function set ...
- alexkn android第一行代码-8.sqlite使用
Android自带sqlite数据库,因此常见操作应该都掌握.包括数据库的创建/升级以及增删改查. 1.创建数据库 public class MyDatabaseHelper extends SQLi ...
- iOS通知
链接: IOS之推送通知(本地推送和远程推送) iOS 10推送通知开发 活久见的重构 - iOS 10 UserNotifications 框架解析 iOS10全新推送功能的实现