文件上传下载
This commit is contained in:
BIN
libs/javax.servlet-api-4.0.1.jar
Normal file
BIN
libs/javax.servlet-api-4.0.1.jar
Normal file
Binary file not shown.
@@ -142,6 +142,7 @@ public class projectService {
|
||||
}
|
||||
|
||||
public projectEntity selectProById(String id ){
|
||||
|
||||
projectEntity projectEntity = projectDao.selectProById(id);
|
||||
categoryEntity categoryEntity = categoryDao.retNum(projectEntity.getCategoryId());
|
||||
projectEntity.setCategoryName(categoryEntity.getCategoryName());
|
||||
|
127
src/com/hellogithub/servlet/DownLoadServlet.java
Normal file
127
src/com/hellogithub/servlet/DownLoadServlet.java
Normal file
@@ -0,0 +1,127 @@
|
||||
package com.hellogithub.servlet;
|
||||
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.annotation.WebServlet;
|
||||
import javax.servlet.http.HttpServlet;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.*;
|
||||
import java.net.URLEncoder;
|
||||
import java.util.HashMap;
|
||||
import java.util.UUID;
|
||||
|
||||
@WebServlet("/DownLoad")
|
||||
public class DownLoadServlet extends HttpServlet {
|
||||
|
||||
|
||||
public void doGet(HttpServletRequest request, HttpServletResponse response)
|
||||
throws ServletException, IOException {
|
||||
response.setCharacterEncoding("UTF-8");
|
||||
response.setContentType("text/html; charset=utf-8");
|
||||
|
||||
String curOrigin = request.getHeader("Origin");
|
||||
response.setHeader("Access-Control-Allow-Origin", curOrigin == null ? "true" : curOrigin);
|
||||
response.setHeader("Access-Control-Allow-Credentials", "true");
|
||||
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, HEAD");
|
||||
response.setHeader("Access-Control-Max-Age", "3600");
|
||||
response.setHeader("Access-Control-Allow-Headers", "access-control-allow-origin, authority, content-type, version-info, X-Requested-With");
|
||||
response.setContentType("application/json;charset=UTF-8");
|
||||
|
||||
|
||||
PrintWriter writer = response.getWriter();
|
||||
|
||||
//得到要下载的文件名
|
||||
String fileName = request.getParameter("filename");
|
||||
System.out.print(fileName);
|
||||
|
||||
//本地需要进行转码,linux服务器使用就会出现下载乱码
|
||||
//fileName = new String(fileName.getBytes("iso8859-1"),"UTF-8");
|
||||
|
||||
// System.out.print("转码后"+fileName);
|
||||
//上传的文件都是保存在/WEB-INF/upload目录下的子目录当中
|
||||
String fileSaveRootPath=this.getServletContext().getRealPath(File.separator+"WEB-INF"+File.separator+"upload");
|
||||
//通过文件名找出文件的所在目录
|
||||
//String path = findFileSavePathByFileName(fileName,fileSaveRootPath);
|
||||
// String path = "/WEB-INF/upload";
|
||||
//得到要下载的文件
|
||||
File file = new File(fileSaveRootPath + File.separator + fileName);
|
||||
//File file = new File(fileName);
|
||||
System.out.print(file);
|
||||
System.out.print("\n");
|
||||
// 浏览器请求响应转码防止乱码
|
||||
response.setCharacterEncoding("UTF-8");
|
||||
request.setCharacterEncoding("UTF-8");
|
||||
//如果文件不存在
|
||||
if(!file.exists()){
|
||||
setResultError("文件资源已被删除",writer);
|
||||
return;
|
||||
}
|
||||
//处理文件名
|
||||
String realname = fileName.substring(fileName.indexOf("_")+1);
|
||||
//设置响应头,控制浏览器下载该文件
|
||||
response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(realname, "UTF-8"));
|
||||
//读取要下载的文件,保存到文件输入流
|
||||
FileInputStream in = new FileInputStream(fileSaveRootPath +File.separator+ fileName);
|
||||
//创建输出流
|
||||
OutputStream out = response.getOutputStream();
|
||||
//创建缓冲区
|
||||
byte buffer[] = new byte[1024];
|
||||
int len = 0;
|
||||
//循环将输入流中的内容读取到缓冲区当中
|
||||
while((len=in.read(buffer))>0){
|
||||
//输出缓冲区的内容到浏览器,实现文件下载
|
||||
out.write(buffer, 0, len);
|
||||
}
|
||||
//关闭文件输入流
|
||||
in.close();
|
||||
//关闭输出流
|
||||
out.close();
|
||||
// setResultOK("下载成功",writer);
|
||||
}
|
||||
|
||||
/**
|
||||
* @Method: findFileSavePathByFileName
|
||||
* @Description: 通过文件名和存储上传文件根目录找出要下载的文件的所在路径
|
||||
* @Anthor:
|
||||
* @param filename 要下载的文件名
|
||||
* @param saveRootPath 上传文件保存的根目录,也就是/WEB-INF/upload目录
|
||||
* @return 要下载的文件的存储目录
|
||||
*/
|
||||
public String findFileSavePathByFileName(String filename,String saveRootPath){
|
||||
// int hashcode = filename.hashCode();
|
||||
// int dir1 = hashcode&0xf; //0--15
|
||||
// int dir2 = (hashcode&0xf0)>>4; //0-15
|
||||
//String dir = saveRootPath + "\\" + dir1 + "\\" + dir2; //upload\2\3 upload\3\5
|
||||
String dir = saveRootPath;
|
||||
File file = new File(dir);
|
||||
if(!file.exists()){
|
||||
//创建目录
|
||||
file.mkdirs();
|
||||
}
|
||||
return dir;
|
||||
}
|
||||
|
||||
public void doPost(HttpServletRequest request, HttpServletResponse response)
|
||||
throws ServletException, IOException {
|
||||
doGet(request, response);
|
||||
}
|
||||
|
||||
public void setResult(Integer code, String msg, PrintWriter writer) {
|
||||
HashMap<String, Object> result = new HashMap<>();
|
||||
result.put("code", code);
|
||||
result.put("msg", msg);
|
||||
String jsonString = JSONObject.toJSONString(result);
|
||||
writer.println(jsonString);
|
||||
writer.close();
|
||||
}
|
||||
|
||||
public void setResultError(String msg, PrintWriter writer) {
|
||||
setResult(500, msg, writer);
|
||||
}
|
||||
|
||||
public void setResultOK(String msg, PrintWriter writer) {
|
||||
setResult(200, msg, writer);
|
||||
}
|
||||
}
|
235
src/com/hellogithub/servlet/UploadHandleServlet.java
Normal file
235
src/com/hellogithub/servlet/UploadHandleServlet.java
Normal file
@@ -0,0 +1,235 @@
|
||||
package com.hellogithub.servlet;
|
||||
|
||||
|
||||
import javax.servlet.annotation.WebServlet;
|
||||
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import org.apache.commons.fileupload.FileItem;
|
||||
import org.apache.commons.fileupload.FileUploadBase;
|
||||
import org.apache.commons.fileupload.ProgressListener;
|
||||
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
|
||||
import org.apache.commons.fileupload.servlet.ServletFileUpload;
|
||||
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.http.HttpServlet;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.*;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
@WebServlet("/UploadHandle")
|
||||
public class UploadHandleServlet extends HttpServlet {
|
||||
public void doGet(HttpServletRequest request, HttpServletResponse response)
|
||||
throws ServletException, IOException {
|
||||
response.setCharacterEncoding("UTF-8");
|
||||
response.setContentType("text/html; charset=utf-8");
|
||||
// 设置响应头允许ajax跨域访问
|
||||
String curOrigin = request.getHeader("Origin");
|
||||
response.setHeader("Access-Control-Allow-Origin", curOrigin == null ? "true" : curOrigin);
|
||||
response.setHeader("Access-Control-Allow-Credentials", "true");
|
||||
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, HEAD");
|
||||
response.setHeader("Access-Control-Max-Age", "3600");
|
||||
response.setHeader("Access-Control-Allow-Headers", "access-control-allow-origin, authority, content-type, version-info, X-Requested-With");
|
||||
response.setContentType("application/json;charset=UTF-8");
|
||||
PrintWriter writer = response.getWriter();
|
||||
|
||||
|
||||
//得到上传文件的保存目录,将上传的文件存放于WEB-INF目录下,不允许外界直接访问,保证上传文件的安全
|
||||
String savePath = this.getServletContext().getRealPath(File.separator+"WEB-INF"+File.separator+"upload");
|
||||
//上传时生成的临时文件保存目录
|
||||
String tempPath = this.getServletContext().getRealPath(File.separator+"WEB-INF"+File.separator+"tmp");
|
||||
File tmpFile = new File(tempPath);
|
||||
if (!tmpFile.exists()) {
|
||||
//创建临时目录
|
||||
tmpFile.mkdir();
|
||||
}
|
||||
//消息提示
|
||||
String message = "";
|
||||
String saveFilename="";
|
||||
try{
|
||||
//使用Apache文件上传组件处理文件上传步骤:
|
||||
//1、创建一个DiskFileItemFactory工厂
|
||||
DiskFileItemFactory factory = new DiskFileItemFactory();
|
||||
|
||||
//设置工厂的缓冲区的大小,当上传的文件大小超过缓冲区的大小时,就会生成一个临时文件存放到指定的临时目录当中。
|
||||
|
||||
factory.setSizeThreshold(1024*100);//设置缓冲区的大小为100KB,如果不指定,那么缓冲区的大小默认是10KB
|
||||
|
||||
//设置上传时生成的临时文件的保存目录
|
||||
factory.setRepository(tmpFile);
|
||||
|
||||
|
||||
//2、创建一个文件上传解析器
|
||||
ServletFileUpload upload = new ServletFileUpload(factory);
|
||||
|
||||
//监听文件上传进度
|
||||
upload.setProgressListener(new ProgressListener(){
|
||||
public void update(long pBytesRead, long pContentLength, int arg2) {
|
||||
System.out.println("文件大小为:" + pContentLength + ",当前已处理:" + pBytesRead);
|
||||
/**
|
||||
* 文件大小为:14608,当前已处理:4096
|
||||
文件大小为:14608,当前已处理:7367
|
||||
文件大小为:14608,当前已处理:11419
|
||||
文件大小为:14608,当前已处理:14608
|
||||
*/
|
||||
}
|
||||
});
|
||||
|
||||
//解决上传文件名的中文乱码
|
||||
upload.setHeaderEncoding("UTF-8");
|
||||
|
||||
//3、判断提交上来的数据是否是上传表单的数据
|
||||
if(!ServletFileUpload.isMultipartContent(request)){
|
||||
//按照传统方式获取数据
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
|
||||
//设置上传单个文件的大小的最大值,目前是设置为1024*1024字节,也就是1MB
|
||||
upload.setFileSizeMax(1024*1024*1024);
|
||||
|
||||
//设置上传文件总量的最大值,最大值=同时上传的多个文件的大小的最大值的和,目前设置为10MB
|
||||
upload.setSizeMax(1024*1024*1024*10);
|
||||
|
||||
//4、使用ServletFileUpload解析器解析上传数据,解析结果返回的是一个List<FileItem>集合,每一个FileItem对应一个Form表单的输入项
|
||||
|
||||
|
||||
List<FileItem> list = upload.parseRequest(request);
|
||||
|
||||
for(FileItem item : list){
|
||||
|
||||
|
||||
//如果fileitem中封装的是普通输入项的数据
|
||||
if(item.isFormField()){
|
||||
String name = item.getFieldName();
|
||||
//解决普通输入项的数据的中文乱码问题
|
||||
String value = item.getString("UTF-8");
|
||||
//String value = new String(name.getBytes("iso8859-1"),"UTF-8");
|
||||
System.out.println(">>>>>>>>>>"+name + "=" + value);
|
||||
|
||||
|
||||
}else{
|
||||
|
||||
//如果fileitem中封装的是上传文件
|
||||
//得到上传的文件名称,
|
||||
String filename = item.getName();
|
||||
//filename = item.getString("UTF-8");
|
||||
//filename = new String(filename.getBytes("iso8859-1"),"UTF-8");
|
||||
System.out.println(filename);
|
||||
if(filename==null || filename.trim().equals("")){
|
||||
continue;
|
||||
}
|
||||
//注意:不同的浏览器提交的文件名是不一样的,有些浏览器提交上来的文件名是带有路径的,如: c:\a\b\1.txt,而有些只是单纯的文件名,如:1.txt
|
||||
//处理获取到的上传文件的文件名的路径部分,只保留文件名部分
|
||||
filename = filename.substring(filename.lastIndexOf(File.separator)+1);
|
||||
//得到上传文件的扩展名
|
||||
String fileExtName = filename.substring(filename.lastIndexOf(".")+1);
|
||||
//如果需要限制上传的文件类型,那么可以通过文件的扩展名来判断上传的文件类型是否合法
|
||||
System.out.println("上传的文件的扩展名是:"+fileExtName);
|
||||
//获取item中的上传文件的输入流
|
||||
InputStream in = item.getInputStream();
|
||||
//得到文件保存的名称
|
||||
saveFilename = makeFileName(filename);
|
||||
|
||||
//得到文件的保存目录
|
||||
String realSavePath = makePath(saveFilename, savePath);
|
||||
System.out.print(realSavePath+"\\"+saveFilename);
|
||||
//创建一个文件输出流
|
||||
FileOutputStream out = new FileOutputStream(realSavePath +File.separator+ saveFilename);
|
||||
//创建一个缓冲区
|
||||
byte buffer[] = new byte[1024];
|
||||
//判断输入流中的数据是否已经读完的标识
|
||||
int len = 0;
|
||||
//循环将输入流读入到缓冲区当中,(len=in.read(buffer))>0就表示in里面还有数据
|
||||
while((len=in.read(buffer))>0){
|
||||
//使用FileOutputStream输出流将缓冲区的数据写入到指定的目录(savePath + "\\" + filename)当中
|
||||
out.write(buffer, 0, len);
|
||||
}
|
||||
//关闭输入流
|
||||
in.close();
|
||||
//关闭输出流
|
||||
out.close();
|
||||
//删除处理文件上传时生成的临时文件
|
||||
item.delete();
|
||||
message = "文件上传成功!";
|
||||
}
|
||||
}
|
||||
}catch (FileUploadBase.FileSizeLimitExceededException e) {
|
||||
e.printStackTrace();
|
||||
setResultError("单个文件超出最大值",writer);
|
||||
return;
|
||||
}catch (FileUploadBase.SizeLimitExceededException e) {
|
||||
e.printStackTrace();
|
||||
setResultError("上传文件的总的大小超出限制的最大值",writer);
|
||||
return;
|
||||
}catch (Exception e) {
|
||||
message= "文件上传失败!";
|
||||
setResultError("文件上传失败",writer);
|
||||
e.printStackTrace();
|
||||
}
|
||||
writer.println(saveFilename);
|
||||
setResultOK(message,writer);
|
||||
}
|
||||
|
||||
/**
|
||||
* @Method: makeFileName
|
||||
* @Description: 生成上传文件的文件名,文件名以:uuid+"_"+文件的原始名称
|
||||
* @Anthor:
|
||||
* @param filename 文件的原始名称
|
||||
* @return uuid+"_"+文件的原始名称
|
||||
*/
|
||||
private String makeFileName(String filename){ //2.jpg
|
||||
//为防止文件覆盖的现象发生,要为上传文件产生一个唯一的文件名
|
||||
return UUID.randomUUID().toString() + "_" + filename;
|
||||
// return filename;
|
||||
}
|
||||
|
||||
/**
|
||||
* 为防止一个目录下面出现太多文件,要使用hash算法打散存储
|
||||
* @Method: makePath
|
||||
* @Description:
|
||||
* @Anthor:
|
||||
*
|
||||
* @param filename 文件名,要根据文件名生成存储目录
|
||||
* @param savePath 文件存储路径
|
||||
* @return 新的存储目录
|
||||
*/
|
||||
private String makePath(String filename,String savePath){
|
||||
String dir = savePath;
|
||||
//File既可以代表文件也可以代表目录
|
||||
File file = new File(dir);
|
||||
//如果目录不存在
|
||||
if(!file.exists()){
|
||||
//创建目录
|
||||
file.mkdirs();
|
||||
}
|
||||
return dir;
|
||||
}
|
||||
|
||||
public void doPost(HttpServletRequest request, HttpServletResponse response)
|
||||
throws ServletException, IOException {
|
||||
|
||||
doGet(request, response);
|
||||
}
|
||||
|
||||
public void setResult(Integer code, String msg, PrintWriter writer) {
|
||||
HashMap<String, Object> result = new HashMap<>();
|
||||
result.put("code", code);
|
||||
result.put("msg", msg);
|
||||
String jsonString = JSONObject.toJSONString(result);
|
||||
writer.println(jsonString);
|
||||
writer.close();
|
||||
}
|
||||
|
||||
public void setResultError(String msg, PrintWriter writer) {
|
||||
setResult(500, msg, writer);
|
||||
}
|
||||
|
||||
public void setResultOK(String msg, PrintWriter writer) {
|
||||
setResult(200, msg, writer);
|
||||
}
|
||||
|
||||
}
|
@@ -38,7 +38,6 @@ public class countNumServlet extends HttpServlet {
|
||||
resp.setHeader("Access-Control-Max-Age", "3600");
|
||||
resp.setHeader("Access-Control-Allow-Headers", "access-control-allow-origin, authority, content-type, version-info, X-Requested-With");
|
||||
resp.setContentType("application/json;charset=UTF-8");
|
||||
|
||||
PrintWriter writer = resp.getWriter();
|
||||
writer.println(projectService.countAll());
|
||||
writer.close();
|
||||
|
20
web/upload.jsp
Normal file
20
web/upload.jsp
Normal file
@@ -0,0 +1,20 @@
|
||||
<%@ page language="java" pageEncoding="UTF-8" contentType="text/html;charset=UTF-8"%>
|
||||
<!DOCTYPE HTML>
|
||||
<html>
|
||||
<head>
|
||||
<title>文件上传</title>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<%request.setCharacterEncoding("UTF-8");%>
|
||||
<form action="${pageContext.request.contextPath}/UploadHandle" enctype="multipart/form-data" method="post">
|
||||
上传用户:<input type="text" name="username"><br/>
|
||||
上传文件1:<input type="file" name="file1"><br/>
|
||||
上传文件2:<input type="file" name="file2"><br/>
|
||||
<input type="submit" value="提交">
|
||||
</form>
|
||||
</body>
|
||||
<body> <br>
|
||||
<input id="btnCancel" class="btn" type="button" value="下载页" onclick="window.location='../FileUploadAndDownLoad/servlet/ListFileServlet'" />
|
||||
</body>
|
||||
</html>
|
Reference in New Issue
Block a user