文件上传

原创 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>

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

两种方法上传本地文件到github

自从使用github以来,一直都是在github网站在线上传文件到仓库中,但是有时因为网络或者电脑的原因上传失败。最重要的原因是我习惯本地编辑,完成以后再一起上传github。看过了几个教程,总结出最...
  • pql925
  • pql925
  • 2017年05月26日 18:30
  • 6848

Javaweb中最简单的文件上传

最简单的文件上传 1、在做之前需要导入的jar包组件: commons-fileupload-1.2.1.jar、commons-io-2.0.jar(依赖包) 2、页面代码 Insert...
  • qq_32079585
  • qq_32079585
  • 2016年05月08日 11:13
  • 39243

HTML5应用之文件上传

HTML5解决了以往网页编写的一个难题:带有上传进度的文件上传。 本文的代码全部来自http://www.matlus.com/html5-file-upload-with-progress...
  • small_rice_
  • small_rice_
  • 2014年03月17日 15:45
  • 69682

在node.js下浅谈文件上传的方法

这是接着上篇文章的下部分,关于文件上传的方法。相对下载,前端部分复杂了不少,接下来就谈谈上传的问题。...
  • liyijun4114
  • liyijun4114
  • 2016年06月28日 14:53
  • 583

JavaWEB+Ajax实现文件上传

准备:我们需要找一张绿色或者其它颜色的背景图,放在photo文件夹里就好哈,然后加jar:common-io和commo-fileupload就可以哈 创建progress.css文件:...
  • u014427391
  • u014427391
  • 2016年04月10日 17:18
  • 10068

SVN客户端上传文件功能的实现

SVN实现文件上传功能,含上传代码,出现错误及异常...
  • jjfly999
  • jjfly999
  • 2016年04月13日 23:43
  • 1908

AngularJS上传文件

使用AngularJS上传文件前台是Angular页面 后台使用SpringBoot/SpirngMVC 上传文件 upload.html 上传 upload.js ...
  • u013360850
  • u013360850
  • 2017年02月26日 17:55
  • 1458

Java实现文件上传

Java实现将本地文件上传到服务器并保存实现文件上传需要用的的jar包:commons-fileupload 和 commons-io1.将form表单的 enctype 设置为:multipart/...
  • hzschqh
  • hzschqh
  • 2017年05月19日 13:47
  • 440

servlet+jsp实现的文件上传与下载

java文件上传与下载      通过微表单元苏设置Method = "post"      enctype = "multipart/form-data"属性,让表单提交的数据以二进制编码的方式...
  • wojiaohuangyu
  • wojiaohuangyu
  • 2016年03月21日 14:51
  • 7301

几种上传文件组件的性能比较

近两天来由于项目需要使用上传组件,于是我仔细分析了Cos和FileUpload的源代码,并对它们的性能进行了测试比较,使用2M、20M、45M、200M的上传大小测试三种组件所花费的时间(单位为ms)...
  • alisafreya
  • alisafreya
  • 2013年08月13日 10:26
  • 1287
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:文件上传
举报原因:
原因补充:

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