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- ...
随机推荐
- Docker入门-Dockerfile的使用
使用Dockerfile定制镜像 镜像的定制实际上就是定制每一层所添加的配置.文件.我们可以把每一层修改.安装.构建.操作的命令都写入一个脚本,这个脚本就是Dockerfile. Dockerfile ...
- js中filter过滤用法总结
定义和用法 filter() 方法创建一个新的数组,新数组中的元素是通过检查指定数组中符合条件的所有元素. 注意: filter() 不会对空数组进行检测. 注意: filter() 不会改变原始数组 ...
- MVC 小demo
.field-validation-error { color: #f00; } .field-validation-valid { display: none; } .input-validatio ...
- SpringMvc中@PathVariable注解简单的用法
@PathVariable /** * @PathVariable 可以来映射 URL 中的占位符到目标方法的参数中. * @param id * @return */ jsp页面请求 <a h ...
- 清明 DAY 4
~~~~~zhx并没有讲完~~~~~~QAQ~~~~~~ (其实并没有更完)
- ansible 剧本进阶 角色
主要内容: playbook(剧本) roles 一.查看收集到的信息 ansible cache -m setup setup (需要了解的参数) ansible_all_ipv4_addresse ...
- Iris Classification on Keras
Iris Classification on Keras Installation Python3 版本为 3.6.4 : : Anaconda conda install tensorflow==1 ...
- leetcode 115不同的子序列
滚动数组: /***** 下标从1开始 dp[i][j]:= numbers of subseq of S[1:j] equals T[1:i] if(s[j]==t[i]):(那么之后的子串可以是是 ...
- Linux 下 *.tar.gz 文件解压缩命令及错误处理
1.压缩命令: 命令格式: tar -zcvf 压缩文件名 .tar.gz 被压缩文件名 可先切换到当前目录下,压缩文件名和被压缩文件名都可加入路径. 2.解压缩命令: 命令格式: tar -zxvf ...
- 下载的管理类MyDownloadManager
import android.content.Intent; import android.net.Uri; import java.io.File; import java.io.FileOutpu ...