JavaWeb中上传和下载文件实例代码
作者:-空星- 时间:2023-11-04 10:24:00
一丶先引入上传下载的lib
二丶上传的的servlet
package com.test.action;
import java.io.File;
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.annotation.WebServlet;
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;
@WebServlet("/upload")
public class FileUpLoadAction extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// 设置编码
request.setCharacterEncoding("utf-8");
//对提交的数据进行处理,保存上传文件
boolean success = processUpload(request);
if(success){
//获取表单text控件的值
String account = request.getAttribute("account").toString();
System.out.println(account);
//获取文件上传的原始名称
String fileName = request.getAttribute("upfile").toString();
System.out.println(fileName);
//获取文件上传后,服务器上保存的名字
String fileNameServer = request.getAttribute("upfileServer").toString();
System.out.println(fileNameServer);
request.setAttribute("upfile", fileNameServer);
request.setAttribute("message", "上传成功");
}
request.getRequestDispatcher("/upload.jsp").forward(request, response);
}
private boolean processUpload(HttpServletRequest request) {
boolean success = true;
String message = null;
// 获取文件需要上传到的路径
String path = request.getServletContext().getRealPath("/upload");
System.out.println(path);
// 如果此文件夹不存在,则构造此文件夹
File f = new File(path);
if (!f.exists()) {
f.mkdir();
}
// 构造出文件工厂,用于存放JSP页面中传递过来的文件
DiskFileItemFactory factory = new DiskFileItemFactory();
// 设置上传文件的保存路径
factory.setRepository(f);
// 设置缓存大小,如果文件大于缓存大小时,则先把文件放到缓存中
factory.setSizeThreshold(1 * 1024 * 1024);
ServletFileUpload upload = new ServletFileUpload(factory);
// 设置可以上传文件大小的上界20MB
upload.setSizeMax(20 * 1024 * 1024);
try {
// 可以上传多个文件
List<FileItem> list = (List<FileItem>) upload.parseRequest(request);
for (FileItem item : list) {
// 获取表单的属性名字
String name = item.getFieldName();
if (item.isFormField()) {
String value = item.getString();
//解决乱码问题
value = new String(value.getBytes("iso-8859-1"),"utf-8");
request.setAttribute(name, value);
} else {
// 获得文件类型
String contentType = item.getContentType();
// 获得文件大小
long fileSize = item.getSize();
// 获取路径名
String value = item.getName();
// 索引到最后一个反斜杠
int start = value.lastIndexOf("\\");
// 截取 上传文件的 字符串名字,加1是 去掉反斜杠,
String filename = value.substring(start + 1);
if (filename != null && !filename.trim().equals("")) {
// 如果上传的文件不是图片,那么不上传
String allImgExt = ".jpg|.jpeg|.gif|.bmp|.png|";
String extName = filename.substring(filename.indexOf("."), filename.length());
if (allImgExt.indexOf(extName + "|") == -1) {
message = "该文件类型不允许上传。请上传 " + allImgExt
+ " 类型的文件,当前文件类型为" + extName;
success = false;
break;
}
request.setAttribute(name, filename);
// 随机数产生名称
String newName = System.currentTimeMillis() + extName;
request.setAttribute(name + "Server", newName);
// 将文件保存到服务器中
InputStream in = item.getInputStream();
// 原文件名
// OutputStream out = new FileOutputStream(new File(path, filename));
// 随机数文件名
OutputStream out = new FileOutputStream(new File(path,
newName));
int length = 0;
byte[] buf = new byte[1024];
while ((length = in.read(buf)) != -1) {
out.write(buf, 0, length);
}
in.close();
out.close();
}
}
}
} catch (FileUploadException e) {
message = "文件的内容过大,请上传小于20MB的文件" ;
success = false;
e.printStackTrace();
} catch (IOException e) {
success = false;
e.printStackTrace();
}
request.setAttribute("message", message);
return success;
}
}
三丶下载的servlet
package com.test.action;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/download")
public class FileDownloadAction extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String id = request.getParameter("id");
// 根据主键读取文件的真实名字 + 服务器上的名字
processDownload("1444442288605.png", "腾讯.png", request, response);
}
private boolean processDownload(String fileName, String saveName,
HttpServletRequest request, HttpServletResponse response) {
boolean success = true;
// 获取文件下载所在的路径
String path = request.getServletContext().getRealPath("/upload");
File fileLoad = new File(path, fileName); // 下载文件
long fileLength = fileLoad.length(); // 文件大小
byte[] buffer = new byte[1024]; // 缓冲字节数组
try {
response.reset();
response.setHeader("Content-disposition", "attachment;filename=\""
+ new String(saveName.getBytes("gb2312"), "ISO-8859-1") + "\"");
response.setContentType("application/octet-stream");
response.setHeader("Content_Length", String.valueOf(fileLength));
OutputStream os = response.getOutputStream();
FileInputStream in = new FileInputStream(fileLoad);
int hasRead = 0;
while ((hasRead = in.read(buffer)) != -1) {
os.write(buffer, 0, hasRead);
}
os.flush();
os.close();
in.close();
} catch (IOException e) {
success = false;
e.printStackTrace();
}
return success;
}
}
以上所述是小编给大家介绍的JavaWeb中上传和下载文件实例代码网站的支持!
来源:http://blog.csdn.net/haitao0823/article/details/73549110
标签:javaweb,上传下载
0
投稿
猜你喜欢
Android ViewPager实现页面左右切换效果
2022-12-28 04:49:35
Flutter构建自定义Widgets的全过程记录
2022-01-27 16:37:39
详解C# 利用反射根据类名创建类的实例对象
2023-12-20 12:42:41
Java学习之线程同步与线程间通信详解
2022-05-27 08:03:59
Android调用系统图库获取图片的方法
2023-09-23 04:13:02
从Python程序中访问Java类的简单示例
2022-02-19 08:53:13
Android 自定义组件成JAR包的实现方法
2023-04-08 17:56:39
Java关于含有继承类的成员初始化过程讲解
2022-09-24 23:25:45
Android 消息队列模型详解及实例
2023-04-06 10:49:43
Android绘制圆形百分比加载圈效果
2023-07-16 17:23:38
Spring Boot+Shiro实现一个Http请求的Basic认证
2022-06-01 22:22:31
C#导入导出EXCEL文件的代码实例
2022-04-21 07:15:15
详解android 中animation-list 动画的应用
2022-09-13 18:28:31
详解JAVA 弱引用
2022-03-12 01:30:29
SpringBoot后端上传文件类型检测方式
2021-07-02 05:00:04
c#中的扩展方法学习笔记
2023-04-11 10:29:15
SpringBoot集成vue的开发解决方案
2023-11-24 20:58:10
Android自定义ViewGroup实现绚丽的仿支付宝咻一咻雷达脉冲效果
2022-10-24 15:42:50
Android无需读写权限通过临时授权读写用户文件详解
2022-11-05 12:50:54
Java 自定义Spring框架以及Spring框架的基本使用
2021-05-29 19:35:57