文件上传,下载案例
文件上传jsp页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<!--
enctype:表单内容提交类型
如果只有普通的文本内容,直接提交成application/x-www-form-urlencoded格式
现在我们的表单中需要含有文件,则需要将表单内容序列化成二进制数据进行提交:multipart/from-data
-->
<form action="register" method="post" enctype="multipart/form-data">
姓名:<input type="text" name="name"><br/>
性别:
<label>
<input type="radio" name="sex" value="女">女
</label>
<label>
<input type="radio" name="sex" value="男">男
</label>
<br/>
<!-- 将文件转换为字节类型的内容 -->
头像:<input type="file" name="touxiang"><br/>
<input type="submit" value="注册">
</form>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="js/jQuery.js"></script>
<script type="text/javascript">
$(function(){
$("#fileBox").change(function(){
//表单元素对象(如果直接取出该元素,JS不能肯定该元素一定是一个表单元素,所以会报错)
//先取得表单对象本身,再从其中取得表单元素,如此JS才能识别到这是一个表单元素
var formData = new FormData($("#f")[0]);
$.ajax({
url:"uplodad02",
type:"post",
data:formData,
dataType:"json",
//内容类型,关闭,multipart/form-data
contentType:false,
//处理数据,关闭之后,我们提交的内容将不会被jQuery处理,而是原样提交
processData:false,
success:function(resData){
$("#imgBox").attr("src","img/"+resData.imgUrl);
},error:function(){
alert("创建异步请求失败");
}
});
});
});
$(function(){
$("#imgBox").click(function(){
$("#fileBox").click();
});
})
</script>
</head>
<body>
<form id="f" action="register" method="post" enctype="multipart/form-data">
头像:<input style="display: none;" id="fileBox" type="file" name="touxiang"><br/>
<img style="width: 300px;height: 500px" id="imgBox" src="img/82521f1a-edad-4bd9-b9f7-186f06c37915.gif">
<input type="submit" value="注册">
</form>
</body>
</html>
注:项目里准备一个文件夹来装相应的文件
文件下载jsp页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<a href="download">点击下载</a>
</body>
</html>
servlet
基础版
package com.zb.servlet;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Collection;
import java.util.UUID;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
@WebServlet("/register")
//注解该Servlet,使该Servlet可以处理Part(File)类型的内容
@MultipartConfig
public class MyFileUploadServlet01 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("AAA");
req.setCharacterEncoding("UTF-8");/*表单的enctype="multipart/form-data",Servlet需要加上@MultipartConfig注解*/
//创建表单,设置提交方式为post
String name = req.getParameter("name");
String sex = req.getParameter("sex");
//String str = req.getParameter("touxiang");
Part part = req.getPart("touxiang");
//获得文件的输入流
InputStream is = part.getInputStream();
//声明一个File对象指向一个具体的文件,用于接收上传的输入流读取到的内容
String oldFileName = part.getSubmittedFileName();
//String suffix = oldFileName.split("\\.")[1];
String suffix = oldFileName.substring(oldFileName.lastIndexOf("."));
String newFileName = UUID.randomUUID().toString()+suffix;
File f = new File("D:/uploadFiles/"+newFileName);
//获得想文件写入数据的输出流
OutputStream os = new FileOutputStream(f);
while(true) {
//声明字节数组容器,存放每次读取的内容
byte[] bts = new byte[1024*1024*5];
//让输入流读取内容,存放到bts字节数组中,如果该方法的返回值为-1,则表示已经读到了文件末尾了,则应该终止读取操作
int len = is.read(bts);
//当读取到文件末尾的时候,整个操作应该终止
if(len<=-1) {
break;
}
//将读取到的内容写入到目标文件
os.write(bts,0,len);
}
//推缓冲区
os.flush();
//关闭流对象,释放资源
is.close();
os.close();
}
}
升级版
package com.zb.servlet;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.channels.ReadPendingException;
import java.util.Collection;
import java.util.UUID;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
@WebServlet("/uplodad02")
//注解该Servlet,使该Servlet可以处理Part(File)类型的内容
@MultipartConfig
public class MyFileServlet02 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String realPath = req.getServletContext().getRealPath("img");
System.out.println(realPath);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
//获得上传文件对象,以及上传的文件流
Part part = req.getPart("touxiang");
InputStream is = part.getInputStream();
//拼接文件名
String oldFileName = part.getSubmittedFileName();
String suffix = oldFileName.substring(oldFileName.lastIndexOf("."));
String newFileName = UUID.randomUUID().toString()+suffix;
//创建写入文件对象,以及写入流
File f = new File(req.getServletContext().getRealPath("img")+"/"+newFileName);
OutputStream os = new FileOutputStream(f);
//循环进行写入操作
while(true) {
byte[] bts = new byte[1024*1024*5];
int len = is.read(bts);
if(len<=-1) {
break;
}
os.write(bts,0,len);
}
//关闭流,释放资源
os.flush();
is.close();
os.close();
//,"":""
resp.getWriter().print("{\"code\":\"true\",\"imgUrl\":\""+newFileName+"\"}");
}
}
文件下载servlet
package com.zb.servlet;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
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 FileDownload extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException {
System.out.println("doGet");
//设置相应内容类型
response.setContentType("multipart/form-data");
//相应头,目的在于设置下载文件的名称以及后缀的指定
response.setHeader("Content-Disposition", "attachment;fileName=wyy.exe");
//获得该文件在程序中进行表示
File f = new File("D:/wyy.exe");
//获得需要传递给用户的文件的输入流
InputStream is = new FileInputStream(f);
//获得向浏览器输出文件的输出流
OutputStream os = response.getOutputStream();
while(true) {
byte[] bts = new byte[1024*1024*5];
int len = is.read(bts);
if(len<=-1) {
break;
}
os.write(bts,0,len);
}
os.flush();
os.close();
is.close();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
}
}