文件上传
关联jar包:
commons-fileupload-1.4.jar.zip
commons-io-2.6.jar.zip
jsmartcom_zh_CN.jar
方法1–smartupload.jar
上传主要两个文件:一个是Servlet文件,还有一个是jsp文件
以下为Servlet文件
package servlet;
import com.jspsmart.upload.File;
import com.jspsmart.upload.SmartUpload;
import com.jspsmart.upload.SmartUploadException;
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 javax.servlet.jsp.JspFactory;
import javax.servlet.jsp.PageContext;
import java.io.IOException;
@WebServlet(urlPatterns = "/uploadtest")
public class UploadServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
try {
//1.创建上传文件的对象
SmartUpload smartUpload = new SmartUpload();
//2.初始化上传操作
//s:为响应错误页面.可以不指定
//b:是否使用session
//i:int 字节
//b1:内存溢出部分是否输出到输出流:true
PageContext pageContext = JspFactory.getDefaultFactory()
.getPageContext(this, req, resp, null, false, 1024, true);
smartUpload.initialize(pageContext);
// 3.上传
smartUpload.upload();
// 4.获取文件信息
File file = smartUpload.getFiles().getFile(0);
String filename = file.getFileName();
String ContentType = file.getContentType();
System.out.println("ContentType"+ContentType);
//获取文本信息
String uname = smartUpload.getRequest().getParameter("uname");
System.out.println("uname="+uname);
//5.指定上传的路径
String uploadpath = "/uploadfiles/" + filename;
System.out.println("uploadpath="+uploadpath);
//6.保存到指定位置
file.saveAs(uploadpath, File.SAVEAS_VIRTUAL);
//7.跳转成功页面
req.setAttribute("filename", filename);
req.getRequestDispatcher("success.jsp").forward(req, resp);
} catch (SmartUploadException e) {
e.printStackTrace();
}
}
}
以下为jsp文件
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>success.jsp --smartupload</h1>
<h2>${message}</h2>
<a href="downloadimg?filename=${filename}">下载</a>
<img src="uploadfiles/${filename}"/>
</body>
</html>
方法2–fileupload
上传主要两个文件:一个是Servlet文件,还有一个是jsp文件
以下为Servlet文件
注意:经过测试发现存储在非临时硬盘上,速度非常慢,会出现HTML页面渲染完成,文件没有上传或执行中的情况,实际开发建议响应走临时,存储服务器走异步。
package servlet;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
@WebServlet(urlPatterns = "/uploadtest2")
public class UploadServlet2 extends HttpServlet {
// 上传配置
private static final int MEMORY_THRESHOLD = 1024 * 1024 * 3; // 3MB
private static final int MAX_FILE_SIZE = 1024 * 1024 * 40; // 40MB
private static final int MAX_REQUEST_SIZE = 1024 * 1024 * 50; // 50MB
// 上传文件存储目录
private static final String UPLOAD_DIRECTORY = "upload";
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 检测是否为多媒体上传
if (!ServletFileUpload.isMultipartContent(request)) {
// 如果不是则停止
PrintWriter writer = response.getWriter();
writer.println("Error: 表单必须包含 enctype=multipart/form-data");
writer.flush();
return;
}
// 配置上传参数
DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
// 设置内存临界值 - 超过后将产生临时文件并存储于临时目录中
diskFileItemFactory.setSizeThreshold(MEMORY_THRESHOLD);
// 设置临时存储目录
diskFileItemFactory.setRepository(new File(System.getProperty("java.io.tmpdir")));
ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
// 设置最大文件上传值
servletFileUpload.setFileSizeMax(MAX_FILE_SIZE);
// 设置最大请求值 (包含文件和表单数据)
servletFileUpload.setSizeMax(MAX_REQUEST_SIZE);
servletFileUpload.setHeaderEncoding("UTF-8");
// 构造临时路径来存储上传的文件
// 这个路径相对当前应用的目录
String uploadPath = getServletContext().getRealPath("/") + File.separator + UPLOAD_DIRECTORY;
/*System.out.println("getServletContext().getRealPath(\"/\")=\n"+getServletContext().getRealPath("/"));
System.out.println("File.separator="+File.separator);
System.out.println("UPLOAD_DIRECTORY="+UPLOAD_DIRECTORY);*/
// 如果目录不存在则创建
File uploadDir = new File(uploadPath);
if (!uploadDir.exists()) {
uploadDir.mkdir();
}
// //构造路径来存储上传的文件
// String uploadfilesPath = this.getClass().getClassLoader().getResource("/").getPath()+
// ".."+File.separator+".."+File.separator+".."+File.separator+".."+File.separator+".."+File.separator+
// "web"+File.separator+"uploadfiles";
System.out.println("classPath="+uploadfilesPath);
// File uploadDir2 = new File(uploadfilesPath);
// // 如果目录不存在则创建
// if (!uploadDir2.exists()) {
// uploadDir2.mkdir();
// }
try {
// 解析请求的内容提取文件数据
@SuppressWarnings("unchecked")
List<FileItem> formItems = servletFileUpload.parseRequest(request);
if (formItems != null && formItems.size() > 0) {
// 迭代表单数据
for (FileItem item : formItems) {
// 处理不在表单中的字段
if (!item.isFormField()) {
String fileName = new File(item.getName()).getName();
String filePath = uploadPath + File.separator + fileName;
File storeFile = new File(filePath);
// 在控制台输出文件的上传路径
// System.out.println(filePath);
// System.out.println(uploadPath +"\n"+ File.separator +"\n"+ fileName);
System.out.println("uploadPath="+uploadPath);
System.out.println("File.separator="+File.separator);
System.out.println("fileName="+fileName);
System.out.println(storeFile);
// 保存文件到硬盘
item.write(storeFile);
// String fileName2 = new File(item.getName()).getName();
// //指定上传的路径
// File uploadPath2=new File(uploadfilesPath+File.separator+fileName2);
// System.out.println("uploadPath2="+uploadPath2);
// //保存到指定位置
// item.write(uploadPath2);
// request.setAttribute("fileName2",
// fileName2);
// 跳转成功页面
request.setAttribute("message",
"文件上传成功!");
request.setAttribute("fileName",
fileName);
// request.setAttribute("fileName2",
// fileName2);
}
}
}
} catch (Exception ex) {
request.setAttribute("message",
"错误信息: " + ex.getMessage());
}
getServletContext().getRequestDispatcher("/message.jsp").forward(
request, response);
//存储文件相对路径
/*String srcPath = System.getProperty("user.dir")+"\\src";
String webPath = System.getProperty("user.dir")+"\\web";
System.out.println("webPath="+webPath);
System.out.println("srcPath="+srcPath);*/
// String filePath2=webPath+ File.separator+"/uploadfiles";
//
/* String uploadfilesPath = this.getClass().getClassLoader().getResource("/").getPath()+
".."+File.separator+".."+File.separator+".."+File.separator+".."+File.separator+".."+File.separator+
"web"+File.separator+"uploadfiles";
// System.out.println("classPath="+uploadfilesPath);
File uploadDir2 = new File(uploadfilesPath);
if (!uploadDir2.exists()) {
uploadDir2.mkdir();
}
try {
// 解析请求的内容提取文件数据
@SuppressWarnings("unchecked")
List<FileItem> formItems = servletFileUpload.parseRequest(request);
if (formItems != null && formItems.size() > 0) {
// 迭代表单数据
for (FileItem item : formItems) {
// 处理不在表单中的字段
if (!item.isFormField()) {
String fileName2 = new File(item.getName()).getName();
//指定上传的路径
File uploadPath2=new File(uploadfilesPath+File.separator+fileName2);
System.out.println("uploadPath2="+uploadPath2);
//保存到指定位置
item.write(uploadPath2);
request.setAttribute("fileName2",
fileName2);
}
}
}
} catch (Exception ex) {
request.setAttribute("message",
"错误信息: " + ex.getMessage());
}
// 跳转到 message.jsp
request.getRequestDispatcher("/message.jsp").forward(request, response);*/
// test1(request);
// test2(request);
// kkb();
}
// private static void kkb() {
// try {
// //1.创建上传文件的对象
// SmartUpload smartUpload=new SmartUpload();
// //2.初始化上传操作
// //i=int 字节 b1内存溢出部分是否输出到输出流:true
// //s为响应错误页面.可以不指定 b:是否使用session
// PageContext pageContext=JspFactory.getDefaultFactory()
// .getPageContext(this,req,resp,null,false,1024,true);
// smartUpload.initialize(pageContext);
// //2.1设置编码
smartUpload.setCharset("utf-8");
3.上传
// smartUpload.upload();
4.获取文件信息
// File file =smartUpload.getFiles().getFile(0);
// String fileName=file.getFileName();
// String ContentType=file.getContentType();
// //5.指定上传的路径
// String uploadpath="/uploadfiles/"+fileName;
// //6.保存到指定位置
// file.saveAs(uploadpath,File.SAVEAS_VIRTUAL);
// //7.跳转成功页面
// req.setAttribute("filename",fileName);
// req.getRequestDispatcher("success.jsp").forward(req,resp);
// } catch (SmartUploadException e) {
// e.printStackTrace();
// }
// }
private static void test2(HttpServletRequest request) throws IOException {
//哔哩哔哩黑马
ServletInputStream servletInputStream= request.getInputStream();//请求正文输入流
Integer len =-1;
byte b[] =new byte[1024];
while((len=servletInputStream.read(b))!=-1){
// System.out.println(new String(b,0,len));
}
servletInputStream.close();
}
private static void test1(HttpServletRequest res) {
/**
* getParameter只能获取正文为
* application/x-www-form-urlencoded
* 类型的数据
*/
String name = res.getParameter("name");
String pic = res.getParameter("pic");
System.out.println("name="+name);
System.out.println("pic="+pic);
}
}
以下为jsp文件
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h2>message.jsp --fileupload</h2>
<h2>${message}</h2>
<a href="downimg?filename=${filename}">下载</a><br>
指定位置存储位置
<img src="uploadfiles/${fileName2}"/><hr>
指定临时存储位置
<img src="upload/${fileName}"/>
</body>
</html>
文件下载
以下为Servlet文件
package servlet;
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.IOException;
import java.net.URLEncoder;
@WebServlet(urlPatterns = "/downloadimg")
public class DownloadServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String filename=req.getParameter("filename");
String path = "/uploadfiles/" + filename;
System.out.println(path);
//设置响应的头信息和响应的类型:
resp.setContentType("application/octet-stream");
//resp.addHeader("Content-Disposition","attachment;filename="+filename);
resp.addHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(filename,"UTF-8"));
//跳转页面
req.getRequestDispatcher(path).forward(req,resp);
//清空缓存区
resp.flushBuffer();
}
}
以下为jsp文件
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>success.jsp --smartupload</h1>
<h2>${message}</h2>
<a href="downloadimg?filename=${filename}">下载</a>
<img src="uploadfiles/${filename}"/>
</body>
</html>
以上为上传下载实例
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/82017.html