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- ...
随机推荐
- Express + Mongoose 极简入门
今天尝试使用express + mongoose,构建了一个简单的Hello world,实现以下功能: 定义mongodb使用的Schema,一个User 访问/输出Hello world 访问/i ...
- C++入门经典-例2.13-左移运算
1:代码如下: // 2.13.cpp : 定义控制台应用程序的入口点. // #include "stdafx.h" #include<iostream> using ...
- leetcode 621 任务调度器 Task Scheduler
给定一个用字符数组表示的 CPU 需要执行的任务列表.其中包含使用大写的 A - Z 字母表示的26 种不同种类的任务.任务可以以任意顺序执行,并且每个任务都可以在 1 个单位时间内执行完.CPU 在 ...
- 浏览器端-W3School-HTML:HTML DOM Script 对象
ylbtech-浏览器端-W3School-HTML:HTML DOM Script 对象 1.返回顶部 1. HTML DOM Script 对象 Script 对象 Script 对象表示 HTM ...
- 基于 Node.js 的服务器自动化部署搭建实录
基于 Node.js 的服务器自动化部署搭建实录 在服务器上安装 Node.js 编写拉取仓库.重启服务器脚本 配置 Github 仓库的 Webhook 设置 配置 Node.js 脚本 其他问题 ...
- Unity3D 打包成Exe文件
Unity发布后一般都会一个exe文件和_data文件以及UnityPlayer.dll,如果把这三个文件整合成一个exe就可以(装逼)了 首先打开Winrar将这三个压缩: 压缩文件名设置为需要启动 ...
- python中sys.argv使用
创建一个脚本,内容如下 [root@bogon ~]# cat a.py #conding:utf-8import sysprint(sys.argv[0]) # 打印sys.argv的第0个参数 执 ...
- 实现 laravel 的artisan
laravel 的 artisan 命令行太好用了,换个框架没有这个功能,于是自己学习实现一些,直接上代码 新建目录 -artisan --bin --src 进入artisan composer i ...
- <数据结构系列2>栈的实现与应用(LeetCode<有效的的括号>)
首先想要实现栈,就得知道栈为何物,以下一段摘抄至百度百科: 栈(stack)又名堆栈,它是一种运算受限的线性表.其限制是仅允许在表的一端进行插入和删除运算.这一端被称为栈顶,相对地,把另一端称为栈底. ...
- 大觅网07day
分布式日志环境的构建(ELK+Kafka) 主要是搭建分布式日志环境,由ELK+Kafka实现,分为以下四步实现: 一.Elasticsearch环境的搭建和测试 1.删除已经存在的ES容器和镜像,如 ...