首页 > 代码库 > 文件上传

文件上传

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>servlet相关类的演示3</title>
</head>

<body>
<h2>文件上传演示</h2>
<h3>过渡版--了解底层</h3>
<form action="<%=request.getContextPath()%>/upload0" method="post"
enctype="multipart/form-data">
文件1:<input type="file" name="file"/><br/>
<input type="submit" value="http://www.mamicode.com/提交"/><br/>
</form>

<h3>使用apache文件上传工具实现文件上传</h3>
<form action="<%=request.getContextPath()%>/upload" method="post"
enctype="multipart/form-data">
文件1:<input type="file" name="file"/><br/>
文件1的说明:<input type="text" name="desc"/><br/>
文件2:<input type="file" name="file"/><br/>
文件2的说明:<input type="text" name="desc"/><br/>
<input type="submit" value="http://www.mamicode.com/提交"/><br/>
</form>
<br/>
<form action="<%=request.getContextPath()%>/upload2" method="post"
enctype="multipart/form-data">
文件1:<input type="file" name="file"/><br/>
文件1的说明:<input type="text" name="desc"/><br/>
文件2:<input type="file" name="file"/><br/>
文件2的说明:<input type="text" name="desc"/><br/>
<input type="submit" value="http://www.mamicode.com/提交"/><br/>
</form>

<h2>进度条前端技术演示</h2>
<div style="border:1px solid red;width:400px;height:30px;">
<div id="dataDiv" style="background: red; width:0%;height:100%"/>
</div>
<button onclick="start();">Start</button>
<button onclick="stop();">Stop</button>
<button onclick="restart();">ReStart</button>
<script type="text/javascript">
var tm,a;
function start(){
tm = window.setInterval(run, 1000);
a=0;
}
function restart(){
window.clearInterval(tm);
tm = window.setInterval(run, 1000);
a=0;
}
function stop(){
window.clearInterval(tm);
}
function run(){
a+=10;
if(a>100){
window.clearInterval(tm);
return;
}
var div = document.getElementById("dataDiv");
div.style.width=a+"%";
}
</script>

<br/><br/><br/><br/>
<img src="http://www.mamicode.com//imgs/1.jpg" /><br/>

<!-- 注意,后台存储的资源文件不允许使用中文,否则前端无法访问的 -->
<img src="http://www.mamicode.com//imgs/图片2.jpg" /><br/>
</body>
</html>

------------------------------------------------------------------------------------------

//这里是查看文件夹里面的内容

package cn.hncu.servlet;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UploadServlet0 extends HttpServlet {

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
InputStream in = request.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String line=null;
while( (line=br.readLine())!=null){
System.out.println(line);
}
}

}

-------------------------------------------------------------------------------------------------------------

package cn.hncu.servlet;

import java.io.File;
import java.io.IOException;
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.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;

public class UploadServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
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>");
//获取GET方式的url中“?”号后面的部分
//http://localhost:8080/servletDemo3/upload?name=Jack&sex=male
String qStr = request.getQueryString();
System.out.println("qStr: "+qStr);//qStr: name=Jack&sex=male

out.println("不支持GET方式上传文件");

out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
}


public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//普通的form表单(POST1: application/x-www-form-urlencoded ),下面这句可以设置普通表单组件内容的编码(能够解决它们的中文乱码问题)
request.setCharacterEncoding("utf-8");//※如果是含上传文件的表单(POST2: multipart/form-data),该句只能设置所上传文件的文件名中的编码(解决它的中文乱码)。但不能解决普通表单组件的乱码(不能设它编码)

//在服务器上,为所有上传文件指定一个存放目录.这个文件是在服务器文件中webapps中发表的项目里面
String path = getServletContext().getRealPath("/upload");
File dir = new File(path);
if(!dir.exists()){
dir.mkdirs();
}

File file = new File("d:/a");
DiskFileItemFactory f = new DiskFileItemFactory(1024*8,file);//设置临时文件缓冲区大小
ServletFileUpload upload = new ServletFileUpload(f);//上传工具
upload.setFileSizeMax(1024*1024*5);//设置单个文件最大为5M
upload.setSizeMax(1024*1024*8);//所有上传文件大小之和的最大值,8M
//使用工具解析
try {
List<FileItem> list = upload.parseRequest(request);
for(FileItem ff:list){
if(ff.isFormField()){//普通表单组件 <input type=text,checkbox,radio,password ...
String desc = ff.getString("utf-8");//※在POST2下,用指定编码的方式解决中文乱码
System.out.println("desc:"+desc);
}else{
//System.out.println("文件内容类型:"+ff.getContentType());
//System.out.println("文件名:"+ff.getName());//上课时间.txt
String fileName = ff.getName();

String uuid = UUID.randomUUID().toString().replace("-", "");
String ext = fileName.substring(fileName.lastIndexOf("."));
String newFileName = uuid+ext;

//FileUtils.copyInputStreamToFile(ff.getInputStream(),new File("d:/a/d/a.txt"));//写死了,后面的文件容易把之前的文件冲掉
FileUtils.copyInputStreamToFile(ff.getInputStream(),new File(path+"/"+newFileName));//写活

}
}

} catch (FileUploadException e) {
e.printStackTrace();
}

}

}

//在上面的url-pattern中的名称是upload

-------------------------------------------------------------------------------------------------------

package cn.hncu.servlet;

import java.io.File;
import java.io.IOException;
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;
import org.apache.commons.io.FileUtils;

public class UploadServlet2 extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
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>");
//获取GET方式的url中“?”号后面的部分
//http://localhost:8080/servletDemo3/upload?name=Jack&sex=male
String qStr = request.getQueryString();
System.out.println("qStr: "+qStr);//qStr: name=Jack&sex=male

out.println("不支持GET方式上传文件");

out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
}


public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//普通的form表单(POST1: application/x-www-form-urlencoded ),下面这句可以设置普通表单组件内容的编码(能够解决它们的中文乱码问题)
request.setCharacterEncoding("utf-8");//※如果是含上传文件的表单(POST2: multipart/form-data),该句只能设置所上传文件的文件名中的编码(解决它的中文乱码)。但不能解决普通表单组件的乱码(不能设它编码)

response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();

//▲1防黑: 防护前端采用POST1方式提交
//法1
/*
String type=request.getContentType();
if(!type.contains("multipart/form-data")){
out.println("不支持普通表单提交");
return;
}
*/

//法2
boolean boo = ServletFileUpload.isMultipartContent(request);
if(!boo){
out.println("不支持普通表单提交");
return;
}


//在服务器上,为所有上传文件指定一个存放目录
String path = getServletContext().getRealPath("/upload");
File dir = new File(path);
if(!dir.exists()){
dir.mkdirs();
}

File file = new File("d:/a");
DiskFileItemFactory f = new DiskFileItemFactory(1024*8,file);//设置临时文件缓冲区大小
ServletFileUpload upload = new ServletFileUpload(f);//上传工具
upload.setFileSizeMax(1024*1024*5);//设置单个文件最大为5M
upload.setSizeMax(1024*1024*8);//所有上传文件大小之和的最大值,8M

//▲4上传进度监听
upload.setProgressListener(new ProgressListener(){
private double pre=0D;
@Override//参数1:已上传多少字节 参数2:一共多少字节 参数3:第几个文件(序号从1开始)
public void update(long pByteRead, long pContentLength, int pItems) {
double d = 1.0*pByteRead/pContentLength*100;
System.out.println(d+"%");
// if(pre!=d){
// System.out.println(d+"%");
// pre=d;
// }
}
});

//使用工具解析
try {
List<FileItem> list = upload.parseRequest(request);
for(FileItem ff:list){
if(ff.isFormField()){//普通表单组件 <input type=text,checkbox,radio,password ...
String desc = ff.getString("utf-8");//※在POST2下,用指定编码的方式解决中文乱码
System.out.println("desc:"+desc);
}else{

//▲2防护: 过滤掉没有选择文件的 空文件组件
//ff.getSize();//返回当前文件的大小
long size = ff.getSize();
//System.out.println("size: "+size);
if(size==0){
continue;
}

//System.out.println("文件内容类型:"+ff.getContentType());
//System.out.println("文件名:"+ff.getName());//上课时间.txt
String fileName = ff.getName();
//System.out.println("************");
String uuid = UUID.randomUUID().toString().replace("-", "");
String ext = fileName.substring(fileName.lastIndexOf("."));
String newFileName = uuid+ext;

//▲3 文件打散技术
String dir1 = Integer.toHexString( uuid.hashCode()&0xf );
String dir2 = Integer.toHexString( (uuid.hashCode()&0xf0)>>4 );
File fDir = new File( path+"/"+dir1+"/"+dir2);
if(!fDir.exists()){
fDir.mkdirs();
}
String path2 = path+"/"+dir1+"/"+dir2;


FileUtils.copyInputStreamToFile(ff.getInputStream(),new File(path2+"/"+newFileName));//写活

}
}

} catch (FileUploadException e) {
e.printStackTrace();
}

}

}

-------------------------------------------------------------------------------------------------

文件上传