jsp+servlet实现文件上传下载
01.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Jsp+Servlet实现文件上传下载</title>
<link rel="stylesheet" type="text/css" href="<%=request.getContextPath() %>/css/common.css" />
<script type="text/javascript" src="<%=request.getContextPath() %>/js/jquery-1.11.1.js"></script>
<script type="text/javascript">
$(function(){
$(".thumbs a").click(function(){
var largePath = $(this).attr("href");
var largeAlt = $(this).attr("title");
$("#largeImg").attr({
src:largePath,
alt:largeAlt
});
return false;
});
/* $("#myfile").change(function(){
$("#previewImg").attr("src", "file:///D:/images/" + $("#myfile").val());
}); */ var la = $("large");
la.hide();
$("#previewImg").mousemove(function(e) {
alert('<img src="' + this.src + '"/>');
la.css({
top:e.pageY,
left:e.pageX
}).html('<img src="' + this.src + '"/>').show();
}).mouseout(function() {
la.hide();
});
});
/*js实现*/
/*function showPreview(obj) {
var str = obj.value;
var a = document.getElementById("myfile").value;
alert(a);
console.log(str);
var divImg = document.getElementById("previewImg");
divImg.innerHTML = "<img src='" + str + "'/>";
}*/
function showPreview(obj) {
var pic = document.getElementById("previewImg");
var file = obj;
if (window.FileReader) {
oFReader = new FileReader();
oFReader.readAsDataURL(file.files[0]);
oFReader.onload = function (oFREvent) {pic.src = oFREvent.target.result;};
}
}
</script>
</head>
<body>
<!--
<form action="">
请选择文件:<input type="file" id="myfile" name="myfile" onchange="showPreview(this)"/>
<div id="previewImg">
</div>
</form>
-->
<img id="previewImg" alt="" src="<%=request.getContextPath() %>/images/preview.jpg" width="80" height="80"/>
<form action="<%=request.getContextPath() %>/uploadServlet" method="post" enctype="multipart/form-data">
请选择文件:<input type="file" id="myfile" name="myfile" accept="image/*" onchange="showPreview(this)" />
<input type="submit" value="提交" />${result}
</form>
<a href="<%=request.getContextPath() %>/downloadServlet?filename=1.txt">1.txt</a> ${errorResult}
<div id="large"></div>
<hr>
<h2>图片预览</h2>
<p>
<img id="largeImg" alt="Large Image" src="<%=request.getContextPath() %>/images/img1-lg.jpg" />
</p>
<p class="thumbs">
<a href="<%=request.getContextPath() %>/images/img2-thumb.jpg" title="Image2"><img src="<%=request.getContextPath() %>/images/img2-thumb.jpg" /></a>
<a href="<%=request.getContextPath() %>/images/img3-thumb.jpg" title="Image3"><img src="<%=request.getContextPath() %>/images/img3-thumb.jpg" /></a>
<a href="<%=request.getContextPath() %>/images/img4-thumb.jpg" title="Image4"><img src="<%=request.getContextPath() %>/images/img4-thumb.jpg" /></a>
<a href="<%=request.getContextPath() %>/images/img5-thumb.jpg" title="Image5"><img src="<%=request.getContextPath() %>/images/img5-thumb.jpg" /></a>
<a href="<%=request.getContextPath() %>/images/img6-thumb.jpg" title="Image6"><img src="<%=request.getContextPath() %>/images/img6-thumb.jpg" /></a>
</p> </body>
</html>
文件上传UploadServlet.java
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile; import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; public class UploadServlet extends HttpServlet { private static final long serialVersionUID = 1L; @Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
this.doPost(req, resp);
} @Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
InputStream fileSource = req.getInputStream();
File tempFile = new File("D:/tempFile");
FileOutputStream outputStream = new FileOutputStream(tempFile);
byte[] b = new byte[1024];
int n;
while ((n = fileSource.read(b)) != -1) {
outputStream.write(b, 0, n);
}
outputStream.close();
fileSource.close(); // 获取上传文件名称
RandomAccessFile randomFile = new RandomAccessFile(tempFile, "r");
randomFile.readLine();
String str = randomFile.readLine();
int beginIndex = str.lastIndexOf("=") + 2;
int endIndex = str.lastIndexOf("\"");
String fileName = str.substring(beginIndex, endIndex);
System.out.println(fileName); // 重新定位文件指针到文件头
randomFile.seek(0);
long startPosition = 0;
int i = 1;
// 获取文件内容
while ((n = randomFile.readByte()) != -1 && i <= 4) {
if (n == '\n') {
startPosition = randomFile.getFilePointer();
i++;
}
}
startPosition = startPosition - 1;
// 获取文件内容结束位置
randomFile.seek(randomFile.length());
long endPosition = randomFile.getFilePointer();
int j = 1;
while (endPosition >= 0 && j <= 2) {
endPosition--;
randomFile.seek(endPosition);
if (randomFile.readByte() == '\n') {
j++;
}
}
// endPosition = endPosition - 1; // 设置保存上传文件的路径
String realPath = getServletContext().getRealPath("/") + "images";
File fileupload = new File(realPath);
if (!fileupload.exists()) {
fileupload.mkdir();
}
File saveFile = new File(realPath, fileName);
RandomAccessFile randomAccessFile = new RandomAccessFile(saveFile, "rw");
// 从临时文件当中读取文件内容(根据起止位置获取)
randomFile.seek(startPosition);
randomFile.readLine();
while(startPosition < endPosition) {
randomAccessFile.write(randomFile.readByte());
startPosition = randomFile.getFilePointer();
}
// 关闭输入输出流,删除临时文件
randomAccessFile.close();
randomFile.close();
tempFile.delete(); req.setAttribute("result", "上传成功!");
RequestDispatcher dispatcher = req.getRequestDispatcher("jsp/01.jsp");
dispatcher.forward(req, resp); } }
文件下载DownloadServlet.java
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream; import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; public class DownloadServlet extends HttpServlet{
private static final long serialVersionUID = 1L; @Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// 获取文件下载路径
String path = getServletContext().getRealPath("/") + "images/";
String fileName = req.getParameter("filename");
File file = new File(path + fileName);
if (file.exists()) {
// 设置相应类型 application/octet-stream
resp.setContentType("application/x-msdownload");
// 设置头信息
resp.setHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
InputStream inputStream = new FileInputStream(file);
ServletOutputStream outputStream = resp.getOutputStream();
byte[] b = new byte[1024];
int n;
while((n = inputStream.read(b)) != -1) {
outputStream.write(b, 0, n);
}
// 关闭流,释放资源
outputStream.close();
inputStream.close();
} else {
req.setAttribute("errorResult", "文件不存在下载失败");
RequestDispatcher dispatcher = req.getRequestDispatcher("jsp/01.jsp");
dispatcher.forward(req, resp);
}
} @Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
this.doGet(req, resp);
} }
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>scxz</display-name> <servlet>
<servlet-name>UploadServlet</servlet-name>
<servlet-class>com.lijy.servlet.UploadServlet</servlet-class>
</servlet> <servlet>
<servlet-name>DowloadServlet</servlet-name>
<servlet-class>com.lijy.servlet.DownloadServlet</servlet-class>
</servlet> <servlet-mapping>
<servlet-name>UploadServlet</servlet-name>
<url-pattern>/uploadServlet</url-pattern>
</servlet-mapping> <servlet-mapping>
<servlet-name>DowloadServlet</servlet-name>
<url-pattern>/downloadServlet</url-pattern>
</servlet-mapping> <welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
jsp+servlet实现文件上传下载的更多相关文章
- 通过JSP+servlet实现文件上传功能
在TCP/IP中,最早出现的文件上传机制是FTP.它将文件由客户端到服务器的标准机制. 但是在JSP中不能使用FTP来上传文件,这是有JSP的运行机制所决定的. 通过为表单元素设置Method=&qu ...
- Servlet中文件上传下载
1.文件下载: package FileUploadAndDown; import java.io.FileInputStream; import java.io.IOException; impor ...
- jsp+servlet实现文件上传
上传(上传不能使用BaseServlet) 1. 上传对表单限制 * method="post" * enctype="multipart/form-data" ...
- Servlet文件上传下载
今天我们来学习Servlet文件上传下载 Servlet文件上传主要是使用了ServletInputStream读取流的方法,其读取方法与普通的文件流相同. 一.文件上传相关原理 第一步,构建一个up ...
- SpringBoot入门一:基础知识(环境搭建、注解说明、创建对象方法、注入方式、集成jsp/Thymeleaf、logback日志、全局热部署、文件上传/下载、拦截器、自动配置原理等)
SpringBoot设计目的是用来简化Spring应用的初始搭建以及开发过程.该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置.通过这种方式,SpringBoot致力于在蓬勃发 ...
- SpringMVC文件上传下载
在Spring MVC的基础框架搭建起来后,我们测试了spring mvc中的返回值类型,如果你还没有搭建好springmvc的架构请参考博文->http://www.cnblogs.com/q ...
- commons-fileupload实现文件上传下载
commons-fileupload是Apache提供的一个实现文件上传下载的简单,有效途径,需要commons-io包的支持,本文是一个简单的示例 上传页面,注意设置响应头 <body> ...
- JavaWeb实现文件上传下载功能实例解析
转:http://www.cnblogs.com/xdp-gacl/p/4200090.html JavaWeb实现文件上传下载功能实例解析 在Web应用系统开发中,文件上传和下载功能是非常常用的功能 ...
- Servlet实现文件上传
一.Servlet实现文件上传,需要添加第三方提供的jar包 下载地址: 1) commons-fileupload-1.2.2-bin.zip : 点击打开链接 2) commons- ...
随机推荐
- [CTS2019]氪金手游
[CTS2019]氪金手游 各种情况加在一起 先考虑弱化版:外向树,wi确定 i合法的概率就是wi/sw sw表示子树的w的和,和子树外情况无关 这些概率乘起来就是最终合法的概率 如果都是外向树, f ...
- [CSP-S模拟测试]:平方数(数学+哈希)
题目传送门(内部题137) 输入格式 第一行,一个正整数$n$. 第二行$n$个正整数$a_1\sim a_n$. 输出格式 输出一个整数,为满足条件的二元组个数. 样例 样例输入: 51 2 3 4 ...
- API网络数据安全
前言 个推作为国内第三方推送市场的早期进入者,专注于为开发者提供高效稳定的服务,在保证稳定的情况下,我们的网络数据交互也达到了一个很高的级别,今天给大家分享的是网络数据安全的常用方法 简介 TCP/I ...
- 误删系统服务Task Schedule的恢复方法
cmd命令 sc query Schedule查询该服务是否存在 sc delete Schedule删除服务 sc create Schedule binpath= "C:\Windows ...
- Zookeeper入门(六)之zkCli.sh对节点的增删改查
参考地址为:https://www.cnblogs.com/sherrykid/p/5813148.html 1.连接 在 bin 目录下的 zkCli.sh 就是ZooKeeper客户端 ./z ...
- 当 LAST_INSERT_ID() 带有参数时# 清空重来
[root@yejr.me]> truncate table t; # 插入1条新记录[root@yejr.me]> insert into t select 0,rand()*1024; ...
- 第五周学习总结&实验报告三
第五周课程总结 1.this和super的区别: this:访问本类中的属性,如果本类没有此属性则从父类中继续查找:访问本类中的方法,如果本类中没有此方法则从父类中继续查找:调用本类构造,必须放在构造 ...
- 让socket端口不被子进程继承
有两个程序A,B A绑定端口8000,然后用system函数启动程序B,然后再把A杀掉,这个时候再重启A的时候会发现绑定端口失败, 原因是端口被B绑定了,实际上是被继承了,为了避免这种情况,需要对主s ...
- Servlet请求参数的方式
今天整理了以下几种常用的Servlet请求参数的方式,下面简单地介绍 1)getParameter(String key)返回一个字符串,获得name和key 一样的表单控件的数据,如果有重复的nam ...
- Reactjs之实现js跳转路由
1.新增知识 /* 实现js跳转路由:https://reacttraining.com/react-router/web/example/auth-workflow 1.要引入Redirect im ...