文件上传

原创 2015年07月07日 23:33:11


2014年9月8日 16:41:10


需要的jar包:commons-fileupload.jar 
                         commons-io.jar


package cn.itcast.upload;
 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
public class UploadServlet1 extends HttpServlet {
 
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// String username = request.getParameter("username");
// String f1 = request.getParameter("f1");
// System.out.println(username);
// System.out.println(f1);
InputStream in = request.getInputStream();//以流的形式获取请求正文中的数据.解析请求正文的内容,进一步处理
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String data = null;
while((data=br.readLine())!=null){
System.out.println(data);
}
br.close();
}
 
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
 
doGet(request, response);
}
 
}





package cn.itcast.upload;
 
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
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.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
//入门案例
public class UploadServlet2 extends HttpServlet {
 
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
//得到存放上传文件的真实路径
String storePath = getServletContext().getRealPath("/files");
//设置环境
DiskFileItemFactory factory = new DiskFileItemFactory();
//判断一下form是否是enctype=multipart/form-data类型的
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if(!isMultipart){
System.out.println("大傻鸟");
return;
}
//ServletFileUpload核心类
ServletFileUpload upload = new ServletFileUpload(factory);
//解析
List<FileItem> items = upload.parseRequest(request);
for(FileItem item:items){
if(item.isFormField()){
//普通字段
String fieldName = item.getFieldName();
String fieldValue = item.getString();
System.out.println(fieldName+"="+fieldValue);
}else{
//上传字段
InputStream in = item.getInputStream();
//上传的文件名
String fileName = item.getName();// C:\Documents and Settings\wzhting\妗岄潰\a.txt a.txt
fileName = fileName.substring(fileName.lastIndexOf("\\")+1);// a.txt
//构建输出流
String storeFile = storePath+"\\"+fileName;
OutputStream out = new FileOutputStream(storeFile);
byte b[] = new byte[1024];
int len = -1;
while((len=in.read(b))!=-1){
out.write(b,0,len);
}
out.close();
in.close();
}
}
} catch (FileUploadException e) {
throw new RuntimeException("服务器忙");
}
}
 
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
 
doGet(request, response);
}
 
}




package cn.itcast.upload;
 
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 java.util.UUID;
 
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.FileUploadException;
import org.apache.commons.fileupload.ProgressListener;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
 
public class UploadServlet3 extends HttpServlet {
 
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
PrintWriter pout = response.getWriter();
try {
// 得到存放上传文件的真实路径
String storePath = getServletContext()
.getRealPath("/WEB-INF/files");
 
// 设置环境
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setRepository(new File(getServletContext().getRealPath("/temp")));//设置临时存放目录
// 判断一下form是否是enctype=multipart/form-data类型的
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (!isMultipart) {
System.out.println("大傻鸟");
return;
}
// ServletFileUpload核心类
ServletFileUpload upload = new ServletFileUpload(factory);
// upload.setProgressListener(new ProgressListener() {
// //pBytesRead:当前以读取到的字节数
// //pContentLength:文件的长度
// //pItems:第几项
// public void update(long pBytesRead, long pContentLength,
// int pItems) {
// System.out.println("已读取:"+pBytesRead+",文件大小:"+pContentLength+",第几项:"+pItems);
// }
//
// });
// upload.setFileSizeMax(4 * 1024 * 1024);// 设置单个上传文件的大小
// upload.setSizeMax(6 * 1024 * 1024);// 设置总文件大小
// 解析
List<FileItem> items = upload.parseRequest(request);
for (FileItem item : items) {
if (item.isFormField()) {
// 普通字段
String fieldName = item.getFieldName();
String fieldValue = item.getString("UTF-8");
System.out.println(fieldName + "=" + fieldValue);
} else {
// 得到MIME类型
String mimeType = item.getContentType();
// 只允许上传图片
if(mimeType.startsWith("image")){
// 上传字段
InputStream in = item.getInputStream();
// 上传的文件名
String fileName = item.getName();// C:\Documents and
if(fileName==null||"".equals(fileName.trim())){
continue;
}
// Settings\wzhting\妗岄潰\a.txt
// a.txt
fileName = fileName
.substring(fileName.lastIndexOf("\\") + 1);// a.txt
fileName = UUID.randomUUID() + "_" + fileName;
System.out.println(request.getRemoteAddr()+"=============="+fileName);
// 构建输出流
// 打散存储目录
String newStorePath = makeStorePath(storePath, fileName);// 根据
// /WEB-INF/files和文件名,创建一个新的存储路径
// /WEB-INF/files/1/12
String storeFile = newStorePath + "\\" + fileName;// WEB-INF/files/1/2/sldfdslf.txt
OutputStream out = new FileOutputStream(storeFile);
byte b[] = new byte[1024];
int len = -1;
while ((len = in.read(b)) != -1) {
out.write(b, 0, len);
}
out.close();
in.close();
item.delete();//删除临时文件
}
}
}
} catch (org.apache.commons.fileupload.FileUploadBase.FileSizeLimitExceededException e) {
// 单个文件超出大小时的异常
pout.write("单个文件大小不能超出4M");
} catch (org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException e) {
// 总文件超出大小时的异常
pout.write("总文件大小不能超出6M");
} catch (Exception e) {
e.printStackTrace();
}
 
}
 
// 根据 /WEB-INF/files和文件名,创建一个新的存储路径 /WEB-INF/files/1/12
private String makeStorePath(String storePath, String fileName) {
int hashCode = fileName.hashCode();
int dir1 = hashCode & 0xf;// 0000~1111:整数0~15共16个
int dir2 = (hashCode & 0xf0) >> 4;// 0000~1111:整数0~15共16个
 
String path = storePath + "\\" + dir1 + "\\" + dir2; // WEB-INF/files/1/12
File file = new File(path);
if (!file.exists())
file.mkdirs();
 
return path;
}
 
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
 
doGet(request, response);
}
 
}





<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>文件上传</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
 
</head>
<body>
<form action="${pageContext.request.contextPath}/servlet/UploadServlet3" method="post" enctype="multipart/form-data">
用户名:<input type="text" name="username"/><br/>
文件1:<input type="file" name="f1"/><br/>
文件2:<input type="file" name="f2"/><br/>
<input type="submit" value="保存"/>
</form>
</body>
</html>

2014年9月8日 16:41:10


需要的jar包:commons-fileupload.jar 
                         commons-io.jar





package cn.itcast.upload;
 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
public class UploadServlet1 extends HttpServlet {
 
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// String username = request.getParameter("username");
// String f1 = request.getParameter("f1");
// System.out.println(username);
// System.out.println(f1);
InputStream in = request.getInputStream();//以流的形式获取请求正文中的数据.解析请求正文的内容,进一步处理
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String data = null;
while((data=br.readLine())!=null){
System.out.println(data);
}
br.close();
}
 
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
 
doGet(request, response);
}
 
}





package cn.itcast.upload;
 
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
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.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
//入门案例
public class UploadServlet2 extends HttpServlet {
 
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
//得到存放上传文件的真实路径
String storePath = getServletContext().getRealPath("/files");
//设置环境
DiskFileItemFactory factory = new DiskFileItemFactory();
//判断一下form是否是enctype=multipart/form-data类型的
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if(!isMultipart){
System.out.println("大傻鸟");
return;
}
//ServletFileUpload核心类
ServletFileUpload upload = new ServletFileUpload(factory);
//解析
List<FileItem> items = upload.parseRequest(request);
for(FileItem item:items){
if(item.isFormField()){
//普通字段
String fieldName = item.getFieldName();
String fieldValue = item.getString();
System.out.println(fieldName+"="+fieldValue);
}else{
//上传字段
InputStream in = item.getInputStream();
//上传的文件名
String fileName = item.getName();// C:\Documents and Settings\wzhting\妗岄潰\a.txt a.txt
fileName = fileName.substring(fileName.lastIndexOf("\\")+1);// a.txt
//构建输出流
String storeFile = storePath+"\\"+fileName;
OutputStream out = new FileOutputStream(storeFile);
byte b[] = new byte[1024];
int len = -1;
while((len=in.read(b))!=-1){
out.write(b,0,len);
}
out.close();
in.close();
}
}
} catch (FileUploadException e) {
throw new RuntimeException("服务器忙");
}
}
 
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
 
doGet(request, response);
}
 
}




package cn.itcast.upload;
 
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 java.util.UUID;
 
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.FileUploadException;
import org.apache.commons.fileupload.ProgressListener;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
 
public class UploadServlet3 extends HttpServlet {
 
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
PrintWriter pout = response.getWriter();
try {
// 得到存放上传文件的真实路径
String storePath = getServletContext()
.getRealPath("/WEB-INF/files");
 
// 设置环境
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setRepository(new File(getServletContext().getRealPath("/temp")));//设置临时存放目录
// 判断一下form是否是enctype=multipart/form-data类型的
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (!isMultipart) {
System.out.println("大傻鸟");
return;
}
// ServletFileUpload核心类
ServletFileUpload upload = new ServletFileUpload(factory);
// upload.setProgressListener(new ProgressListener() {
// //pBytesRead:当前以读取到的字节数
// //pContentLength:文件的长度
// //pItems:第几项
// public void update(long pBytesRead, long pContentLength,
// int pItems) {
// System.out.println("已读取:"+pBytesRead+",文件大小:"+pContentLength+",第几项:"+pItems);
// }
//
// });
// upload.setFileSizeMax(4 * 1024 * 1024);// 设置单个上传文件的大小
// upload.setSizeMax(6 * 1024 * 1024);// 设置总文件大小
// 解析
List<FileItem> items = upload.parseRequest(request);
for (FileItem item : items) {
if (item.isFormField()) {
// 普通字段
String fieldName = item.getFieldName();
String fieldValue = item.getString("UTF-8");
System.out.println(fieldName + "=" + fieldValue);
} else {
// 得到MIME类型
String mimeType = item.getContentType();
// 只允许上传图片
if(mimeType.startsWith("image")){
// 上传字段
InputStream in = item.getInputStream();
// 上传的文件名
String fileName = item.getName();// C:\Documents and
if(fileName==null||"".equals(fileName.trim())){
continue;
}
// Settings\wzhting\妗岄潰\a.txt
// a.txt
fileName = fileName
.substring(fileName.lastIndexOf("\\") + 1);// a.txt
fileName = UUID.randomUUID() + "_" + fileName;
System.out.println(request.getRemoteAddr()+"=============="+fileName);
// 构建输出流
// 打散存储目录
String newStorePath = makeStorePath(storePath, fileName);// 根据
// /WEB-INF/files和文件名,创建一个新的存储路径
// /WEB-INF/files/1/12
String storeFile = newStorePath + "\\" + fileName;// WEB-INF/files/1/2/sldfdslf.txt
OutputStream out = new FileOutputStream(storeFile);
byte b[] = new byte[1024];
int len = -1;
while ((len = in.read(b)) != -1) {
out.write(b, 0, len);
}
out.close();
in.close();
item.delete();//删除临时文件
}
}
}
} catch (org.apache.commons.fileupload.FileUploadBase.FileSizeLimitExceededException e) {
// 单个文件超出大小时的异常
pout.write("单个文件大小不能超出4M");
} catch (org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException e) {
// 总文件超出大小时的异常
pout.write("总文件大小不能超出6M");
} catch (Exception e) {
e.printStackTrace();
}
 
}
 
// 根据 /WEB-INF/files和文件名,创建一个新的存储路径 /WEB-INF/files/1/12
private String makeStorePath(String storePath, String fileName) {
int hashCode = fileName.hashCode();
int dir1 = hashCode & 0xf;// 0000~1111:整数0~15共16个
int dir2 = (hashCode & 0xf0) >> 4;// 0000~1111:整数0~15共16个
 
String path = storePath + "\\" + dir1 + "\\" + dir2; // WEB-INF/files/1/12
File file = new File(path);
if (!file.exists())
file.mkdirs();
 
return path;
}
 
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
 
doGet(request, response);
}
 
}





<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>文件上传</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
 
</head>
<body>
<form action="${pageContext.request.contextPath}/servlet/UploadServlet3" method="post" enctype="multipart/form-data">
用户名:<input type="text" name="username"/><br/>
文件1:<input type="file" name="f1"/><br/>
文件2:<input type="file" name="f2"/><br/>
<input type="submit" value="保存"/>
</form>
</body>
</html>

版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

struts文件上传

  • 2017年11月06日 14:47
  • 3KB
  • 下载

文件上传的jar

  • 2017年11月15日 16:53
  • 217KB
  • 下载

网络编程之get,post请求,文件上传及下载

* 1.发送GET请求 AsyncHttpClient.get(), 使用RequestParams传递数据   * 2.发送POST请求 AsyncHttpClient.post(), 使用R...

文件上传工具类

  • 2017年11月08日 09:35
  • 6KB
  • 下载

FTP 协议和 HTTP 协议的12点比较(文件上传/下载)

许多站点,比如facebook或一些博客等都允许用户上传或下载文件,比如论坛或博客系统的图片。在这种情况下,通常有两种选择上传文件到服务器,那就是FTP协议和HTTP协议。 以下列出了一些两者的...
  • zjdns
  • zjdns
  • 2016年12月20日 19:15
  • 1634

zuixinPHP文件上传和下载示例

  • 2017年11月14日 11:32
  • 1KB
  • 下载

laravel5 文件上传

今天呢学习君在学习的过程中给大家带来了laravel5框架的文件上传   , 希望能和大家共同学习共同进步! 首先呢 大家先明白  计算机中文件上传呢需要哪些参数  1.原文件临时存储绝对路径...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:文件上传
举报原因:
原因补充:

(最多只允许输入30个字)