java实现文件的上传和下载
1. java原生servlet实现:
- web.xml配置:
@WebServlet("/UploadServlet")
public class UploadServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
//根据文件扩展名设置文件MIME类型
resp.setContentType(getServletContext().getMimeType("hello.txt"));
//设置下载消息响应,提示文件保存attachment
resp.setHeader("Content-Disposition", "attachment;filename=" + "hello");
/*
* 设置缓冲区
* is.read(b)当文件读完时返回-1
*/
try {
//输入流为项目文件,输出流指向浏览器
InputStream is = new FileInputStream("E:\\hello.txt");
// 提供了将二进制数据写入响应的流
ServletOutputStream os = resp.getOutputStream();
int len = -1;
byte[] b = new byte[1024];
while ((len = is.read(b)) != -1) {
os.write(b, 0, len);
}
//关闭流
is.close();
os.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
// 文件上传到本地磁盘工厂类
DiskFileItemFactory factory = new DiskFileItemFactory();
//设置内存缓冲区的大小
factory.setSizeThreshold(20480);
//设置临时文件目录,供上传文件过大时临时存储
factory.setRepository(new File("F:\\f"));
//文件上传操作核心类
ServletFileUpload upload = new ServletFileUpload(factory);
//设置限制单个上传文件的大小
upload.setFileSizeMax(50480);
//设置限制总上传文件大小
upload.setSizeMax(80480);
// 这个路径相对当前应用的目录
try {
List<FileItem> formItems = upload.parseRequest(req);
if (formItems != null && formItems.size() > 0) {
// 迭代表单数据
for (FileItem item : formItems) {
// 处理不在表单中的字段
if (!item.isFormField()) {
File storeFile = new File("F:\\fromweb_" + item.getName());
// 保存文件到硬盘
item.write(storeFile);
}
}
}
} catch (FileUploadException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
2. java web主流框架【ssm】实现:
- web.xml配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
<!-- 启动SpringMVC的注解功能 -->
<mvc:annotation-driven/>
<!-- 扫描controller(controller层注入) -->
<context:component-scan base-package="pers.chaffee.controller"/>
<!-- 对模型视图添加前后缀 -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/view/jsp/" p:suffix=".jsp"/>
<!-- 静态资源不走controller -->
<mvc:resources mapping="/resources/**" location="/resources/"/>
</beans>
小结
功能介绍
文件和目录下载
Linux控件安装教程与演示说明:
Linux:http://t.cn/Aijg6fRV
jsp-myeclipse:http://t.cn/Ai9p3IdC
jsp-文件管理器教程:http://t.cn/AiNhmilv