java中的接口是类吗
358
2023-04-08
servlet实现文件上传、预览、下载、删除功能
servlet实现文件上传,预览,下载和删除,供大家参考,具体内容如下
一、准备工作:
1.1 文件上传插件:uploadify;
1.2 文件上传所需jar包:commons-fileupload-1.3.1.jar和commons-io-2.2.jar
1.3 将数据转成jsON对象需要jar包:commons-beanutils-1.8.3.jar、commons-collections-3.2.1.jar、commons-lang-2.6.jar、commons-logging-1.1.3.jar、ezmorph-1.0.6.jar和json-lib-2.4-jdk15.jar
1.4 开发工具:我用的是Eclipse,随意
1.5 目录结构
需要注意的是:变更uploadify.css文件中的取消文件上传图片的路径
.uploadify-queue-item .cancel a {
background: url('../images/uploadify-cancel.png') 0 0 no-repeat;
float: right;
height: 16px;
text-indent: -9999px;
width: 16px;
}
二、代码展示
2.1 客户端代码设计
JSP部分
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
">
">
" type="text/css" rel="stylesheet"/>
">
/* 上传、取消上传按钮style start */
.Button {
width: 80px;
margin: 3px 1px 0 5px;
padding: 0 10px;
background-color: #16a0d3;
border: none;
display: inline-block;
font-family: "Microsoft Yahei";
font-size: 14px;
cursor: pointer;
height: 30px;
line-height: 30px;
color: #FFF;
border-radius: 5px;
text-decoration:none;
text-align:center;
}
.ButtonOver {
width: 80px;
margin: 3px 1px 0 5px;
padding: 0 10px;
background-color: #117ea6;
border: none;
display: inline-block;
font-family: "Microsoft Yahei";
font-size: 14px;
cursor: pointer;
height: 30px;
line-height: 30px;
color: #FFF;
border-radius: 5px;
text-decoration:none;
text-align:center;
}
/* end 上传、取消上传按钮style */
onmouseover="javascript:this.className='ButtonOver'" onmouseout="javascript:this.className='Button'">
上传所有
onmouseover="javascript:this.className='ButtonOver'" onmouseout="javascript:this.className='Button'">
取消上传
序号 文件名 文件预览 文件下载 文件删除
js文件
2.2 服务器端代码设计
文件上传代码(FileUpload.javae文件)
package controller.fileHandler;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletContext;
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 net.sf.json.JSONObject;
public class FileUpload extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
/**
* 处理文件上传的post
* @precaution 下方的类名出自包import org.apache.commons.fileupload.*
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 1.设置参数编码
request.setCharacterEncoding("UTF-8");
// 设置响应数据字符集
response.setCharacterEncoding("UTF-8");
// 设置响应数据格式
// response.setContentType("application/json; charset=UTF-8");
PrintWriter out = response.getWriter();
// 2.创建文件上传处理工厂
DiskFileItemFactory factory = new DiskFileItemFactory();
// 3.设置临时文件存放地点
// 3.1获取当前web应用程序对象(WEB容器在启动时,它会为每个WEB应用程序都创建一个对应的ServletContext对象,它代表当前web应用)
ServletContext servletContext = this.getServletConfig().getServletContext();
// 3.2获取服务器的临时目录(tomcat、WebLogic)
// D:\ProgramFiles(x86)\APACHE\TOMCAT\apache-tomcat-7.0.40-x86\work\Catalina\localhost\demo
File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
// 3.3临时文件将会存储在该目录下
factory.setRepository(repository);
// 4.创建文件上传处理器
ServletFileUpload upload = new ServletFileUpload(factory);
// 5.判断请求类型是否为文件上传类型
boolean multipartContent = upload.isMultipartContent(request);
Map
// 返回信息
String msg = "";
// 错误信息
String errorMsg = "";
// 文件名
String fileName = "";
if (multipartContent) {
try {
// 获取请求参数
String param = request.getParameter("param1");
System.out.println(param);
// 6.解析请求信息
List
// 7.对所有请求信息进行判断
Iterator
while (iter.hasNext()) {
FileItem item = iter.next();
// 信息为文件格式
if (!item.isFormField()) {
fileName = processUploadedFile(param, item);
msg = "上传成功!";
}
}
} catch (FileUploadException e) {
e.printStackTrace();
msg = "上传失败!";
errorMsg = e.getMessage();
}
} else {
msg = "form表单类型不是multipart/form-data,无法上传!";
}
mapData.put("msg", msg);
mapData.put("errorMsg", errorMsg);
mapData.put("fileName", fileName);
// 将Map转成JSON
JSONObject jsonData = JSONObject.fromObject(mapData);
// 返回客户端信息
out.print(jsonData.toString());
}
/**
* 处理上传的文件
* @param ORG_ID
* @param order
* @param item
*/
@SuppressWarnings("unused")
private String processUploadedFile(String param, FileItem item) {
// Process a file upload
String fieldName = item.getFieldName();// 默认值为Filedata
// 获取文件名
String fileName = item.getName();
// 内容类型:application/octet-stream
String contentType = item.getContentType();
boolean isInMemory = item.isInMemory();
// 获取文件大小
long sizeInBytes = item.getSize();
// 1.指定文件上传的根路径
String path = this.getServletContext().getRealPath("/WEB-INF/uploadFiles");
// 2.路径构成:/uploadfile/fileName
// TODO 可以自定义文件存放路径
// 3.根据路径批量创建文件夹
File fileDirectories = new File(path);
// 目录不存在时,再创建
if (!fileDirectories.exists()) {
fileDirectories.mkdirs();// 所有的文件夹都创建成功才返回TRUE
}
// 4.文件名格式校验(文件名中不能包含#号)
int index = fileName.indexOf("#");
if (index > -1) {
fileName = fileName.replace('#', '_');
}
// TODO 可以对文件名进行重命名
// 5.在指定路径下创建指定名称的文件
File uploadedFile = new File(path + "/" + fileName);
// 6.判断该文件是否已存在
if (!uploadedFile.exists()) {
try {
// 使用了这个方法写入文件,临时文件会被系统自动删除
item.write(uploadedFile);
} catch (Exception e) {
e.printStackTrace();
}
}
// 返回重名后的文件名
return fileName;
}
/**
* 处理信息为普通的格式
* @param item
*/
private void processFormField(FileItem item) {
// Process a regular form field
if (item.isFormField()) {
String name = item.getFieldName();
String value = item.getString();
}
}
}
文件查看代码(FileView.java文件)
package controller.fileHandler;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class FileView extends HttpServlet {
private static final long serialVersionUID = 1L;
// 设定输出的类型
private static final String GIF = "image/gif;charset=UTF-8";
private static final String JPG = "image/jpeg;charset=UTF-8";
private static final String PNG = "image/png;charset=UTF-8";
private static final String PDF = "application/pdf;charset=UTF-8";
private static final String ZIP = "application/zip;charset=UTF-8";
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
/**
* 处理文件查看的post
* @throws IOException
* @precaution 下方的类名出自包import org.apache.commons.fileupload.*
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 文件流
InputStream is = null;
// 输入缓冲流
BufferedInputStream bis = null;
// 得到输出流
OutputStream output = null;
// 输出缓冲流
BufferedOutputStream bos = null;
// 1.设置参数编码
request.setCharacterEncoding("UTF-8");
// 2.设置响应数据字符集
response.setCharacterEncoding("UTF-8");
// 3.获取客户端请求参数:文件名
String fileName = request.getParameter("fileName");
// 4.重置response
response.reset();
// 5.设置响应数据格式
if (fileName.endsWith(".gif")) {
response.setContentType(GIF);
} else if (fileName.endsWith(".jpg")) {
response.setContentType(JPG);
} else if (fileName.endsWith(".png")) {
response.setContentType(PNG);
} else if (fileName.endsWith(".pdf")) {
response.setContentType(PDF);
} else if (fileName.endsWith(".gif")) {
response.setContentType(GIF);
} else if (fileName.endsWith(".zip")) {
response.setContentType(ZIP);
}
String filePath = "WEB-INF/uploadFiles/" + fileName;
// 获取当前web应用程序
ServletContext webApp = this.getServletContext();
// 6.获取指定文件上传的真实路径
filePath = webApp.getRealPath(filePath);
// 7.读取目标文件,通过response将目标文件写到客户端
is = new FileInputStream(filePath);
bis = new BufferedInputStream(is);
output = response.getOutputStream();
bos = new BufferedOutputStream(output);
byte data[] = new byte[1024];// 缓冲字节数
int size = bis.read(data);
while (size != -1) {
bos.write(data, 0, size);
size = bis.read(data);
}
// 关闭流
bis.close();
bos.flush();// 清空输出缓冲流
bos.close();
output.close();
}
}
文件下载代码(FileDownload.java文件)
package controller.fileHandler;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class FileDownload extends HttpServlet {
private static final long serialVersionUIhttp://D = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
/**
* 处理文件下载的post
* @throws IOException
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 1.设置参数编码
request.setCharacterEncoding("UTF-8");
// 设置响应数据字符集
response.setCharacterEncoding("UTF-8");
// 1.获得请求文件名
String fileName = request.getParameter("fileName");
// 2.设置文件MIME类型(指定要返回内容的类型)
response.setContentType(getServletContext().getMimeType(fileName));
// 3.设置Content-Disposition(指定下载该文件时的文件名)
response.setHeader("content-disposition", "attachment;filename=" + fileName);
// 4.读取目标文件,通过response将目标文件写到客户端
// 4.1 获取目标文件的绝对路径
String filePath = "WEB-INF/uploadFiles/" + fileName;
filePath = this.getServletContext().getRealPath(filePath);
// 4.2 读取文件
InputStream in = new FileInputStream(filePath);
// 4.3 输出文件
OutputStream out = response.getOutputStream();
// 写文件
int n;
while ((n = in.read()) != -1) {
out.write(n);
}
in.close();
out.close();
}
}
文件删除代码(FileDelete.java文件)
package controller.fileHandler;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class FileDelete extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
/**
* 处理文件下载的post
* @throws IOException
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 1.设置参数编码
request.setCharacterEncoding("UTF-8");
// 设置响应数据字符集
response.setCharacterEncoding("UTF-8");
// 2.获得请求文件名
String fileName = request.getParameter("fileName");
// 3.获取该文件所在路径
String filePath = "WEB-INF/uploadFiles/" + fileName;
filePath = this.getServletContext().getRealPath(filePath);
// 4.在指定路径下创建指定名称的文件
File deleteFile = new File(filePath);
boolean flag = false;
String msg = "";
// 5.判断该文件是否已存在
if (deleteFile.exists()) {
flag = deleteFile.delete();
if (flag) {
msg = "删除成功!";
} else {
msg = "删除失败!";
}
} else {
msg = "该文件不存在!";
}
// 6.返回客户端操作信息
response.getWriter().print(msg);
}
}
web.xml代码
2.3 代码优化
处理文件查看(FileView.java) ,设置响应文件类型,可以用下面这句话替换
response.setContentType(getServletContext().getMimeType(fileName) + ";charset=UTF-8");
三、效果展示
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~