学妹哭着找你教的Javaweb的文件上传与下载
一文件上传要求
1.编写一个包含表单的JSP文件,AddBook.jsp,其页面显示效果如下图,通过表单
可以输入图书的相关信息,并选择图书的封面照片上传。表单的action为AddBookServlet。
请注意表单enctype属性和method属性的设置。
2.编写一个JavaBean类Book,包含与数据库表book_inf的字段对应的
isbn,bookName,auther,publisher,price,amount,typeId,photo属性。用作VO(ValueObject)。
3.编写一个Servlet类AddBookServlet,该类接受AddBook.jsp表单传来的数据和图
片文件,将图片文件以书号为文件基本名,扩展名不变,保存到项目的imgs文件夹中(如:
书号为00000003的图书,上传的图片文件为“Java程序设计.jpg”,则以文件名”
00000003.jpg“保存,以避免与其他图书的图片文件重名),将图书的基本数据保存到数据库
表book_inf中,并创建相应图书的JavaBean对象book,存入request,之后转到
ShowBook.jsp。
4.编写ShowBook.jsp页面,从request中获取book,显示刚刚添加的图书的详细信息,
二文件上传的servlet
import java.io.IOException;
import java.sql.*;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.jspsmart.upload.SmartUpload;
import com.jspsmart.upload.SmartUploadException;
import test10.Book;
@WebServlet("/AddBookServlet")
public class AddBookServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
//实例化对象
SmartUpload smartUpload = new SmartUpload();
// String oldFileName="";
ServletConfig config = getServletConfig();
// 初始化
smartUpload.initialize(config, request, response);
try {
smartUpload.upload();//上传文件
com.jspsmart.upload.File smartFile = smartUpload.getFiles().getFile(0); //获取上传文件
String isbn = smartUpload.getRequest().getParameter("isbn");//获取表单输入语句
String bookName = smartUpload.getRequest().getParameter("bookName");
String author = smartUpload.getRequest().getParameter("auther");
String publisher = smartUpload.getRequest().getParameter("publisher");
String amount = smartUpload.getRequest().getParameter("amount");
String typeld = smartUpload.getRequest().getParameter("typeld");
String price = smartUpload.getRequest().getParameter("price");
String oldFileName=smartFile.getFieldName();
//保存的文件名
String photoFileName =isbn+"."+ smartFile.getFileExt();//获取扩张名
System.out.println("photoFileName=" + photoFileName);
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/bookstore?serverTimezone=Asia/Shanghai";
String sql = "insert into book_info (isbn,bookName,auther,publisher,price,amount,typeld,photo) values(?,?,?,?,?,?,?,?)";
Connection conn = DriverManager.getConnection(url, "test", "123456");
Statement stmt=conn.createStatement();
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, isbn);
ps.setString(2, bookName);
ps.setString(3, author);
ps.setString(4,publisher);
ps.setString(5, price);
ps.setString(6, amount);
ps.setString(7, typeld);
ps.setString(8, photoFileName);
ps.executeUpdate();//将数据插入到数据库中
ps.close();
conn.close();
smartFile.saveAs("imges/"+photoFileName,SmartUpload.SAVE_VIRTUAL);//保存上传文件的路径
Book book=new Book();
book.setIsbn(isbn);
book.setBookName(bookName);
book.setAuther(author);
book.setPublisher(publisher);
book.setAmount(amount);
book.setTypeld(typeld);
book.setPhoto(photoFileName);
request.setAttribute("book", book);
} catch (SmartUploadException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
RequestDispatcher rd=request.getRequestDispatcher("ShowBook.jsp");
rd.forward(request,response);
}
}
*创建一个实体类Book
import java.io.IOException;
import java.sql.*;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.jspsmart.upload.SmartUpload;
import com.jspsmart.upload.SmartUploadException;
import test10.Book;
@WebServlet("/AddBookServlet")
public class AddBookServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
//实例化对象
SmartUpload smartUpload = new SmartUpload();
// String oldFileName="";
ServletConfig config = getServletConfig();
// 初始化
smartUpload.initialize(config, request, response);
try {
smartUpload.upload();//上传文件
com.jspsmart.upload.File smartFile = smartUpload.getFiles().getFile(0); //获取上传文件
String isbn = smartUpload.getRequest().getParameter("isbn");//获取表单输入语句
String bookName = smartUpload.getRequest().getParameter("bookName");
String author = smartUpload.getRequest().getParameter("auther");
String publisher = smartUpload.getRequest().getParameter("publisher");
String amount = smartUpload.getRequest().getParameter("amount");
String typeld = smartUpload.getRequest().getParameter("typeld");
String price = smartUpload.getRequest().getParameter("price");
String oldFileName=smartFile.getFieldName();
//保存的文件名
String photoFileName =isbn+"."+ smartFile.getFileExt();//获取扩张名
System.out.println("photoFileName=" + photoFileName);
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/bookstore?serverTimezone=Asia/Shanghai";
String sql = "insert into book_info (isbn,bookName,auther,publisher,price,amount,typeld,photo) values(?,?,?,?,?,?,?,?)";
Connection conn = DriverManager.getConnection(url, "test", "123456");
Statement stmt=conn.createStatement();
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, isbn);
ps.setString(2, bookName);
ps.setString(3, author);
ps.setString(4,publisher);
ps.setString(5, price);
ps.setString(6, amount);
ps.setString(7, typeld);
ps.setString(8, photoFileName);
ps.executeUpdate();//将数据插入到数据库中
ps.close();
conn.close();
smartFile.saveAs("imges/"+photoFileName,SmartUpload.SAVE_VIRTUAL);//保存上传文件的路径
Book book=new Book();
book.setIsbn(isbn);
book.setBookName(bookName);
book.setAuther(author);
book.setPublisher(publisher);
book.setAmount(amount);
book.setTypeld(typeld);
book.setPhoto(photoFileName);
request.setAttribute("book", book);
} catch (SmartUploadException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
RequestDispatcher rd=request.getRequestDispatcher("ShowBook.jsp");
rd.forward(request,response);
}
}
文件上传并且分配一个实时文件夹
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.List;
import java.util.UUID;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import com.mysql.jdbc.Statement;
@WebServlet("/AddBookServlet")
public class AddBookServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//得到上传文件的保存目录,将上传的文件存放于WEB-INF目录下,不允许外界直接访问,保证上传文件的安全
String savePath = this.getServletContext().getRealPath("/imges");
//上传时生成的临时文件保存目录
try{
//使用Apache文件上传组件处理文件上传步骤:
//1、创建一个DiskFileItemFactory工厂
DiskFileItemFactory factory = new DiskFileItemFactory();
//设置工厂的缓冲区的大小,当上传的文件大小超过缓冲区的大小时,就会生成一个临时文件存放到指定的临时目录当中。
factory.setSizeThreshold(1024*1024*2);//设置缓冲区的大小为2KB,如果不指定,那么缓冲区的大小默认是10KB
//2、创建一个文件上传解析器
ServletFileUpload upload = new ServletFileUpload(factory);
//监听文件上传进度
//解决上传文件名的中文乱码
upload.setHeaderEncoding("UTF-8");
//3、判断提交上来的数据是否是上传表单的数据
if(!ServletFileUpload.isMultipartContent(request)){
//按照传统方式获取数据
return;
}
//设置上传单个文件的大小的最大值,目前是设置为1024*1024字节,也就是1MB
upload.setFileSizeMax(1024*1024);
//设置上传文件总量的最大值,最大值=同时上传的多个文件的大小的最大值的和,目前设置为10MB
upload.setSizeMax(1024*1024*10);
//4、使用ServletFileUpload解析器解析上传数据,解析结果返回的是一个List<FileItem>集合,每一个FileItem对应一个Form表单的输入项
List<FileItem> list = upload.parseRequest(request);
for(FileItem item : list){
//如果fileitem中封装的是普通输入项的数据
if(item.isFormField()){
String name = item.getFieldName();
//解决普通输入项的数据的中文乱码问题
String value = item.getString("UTF-8");
String isbn=request.getParameter("isbn");
String bookName=request.getParameter("bookName");
String auther=request.getParameter("auther");
String publisher=request.getParameter("publisher");
String price=request.getParameter("price");
String amount=request.getParameter("amount");
String typeld=request.getParameter("typeld");
Class.forName("com.mysql.jdbc.Driver");
String url ="jdbc:mysql://localhost:3306/bookstore?serverTimezone=Asia/Shanghai";
//3306为MySql的端口号,dalong为数据库名,root为数据库用户名,其密码为123456
Connection conn= DriverManager.getConnection(url,"test","123456");
Statement stmt=(Statement) conn.createStatement();
String sql="INSERT INTO BOOK_INFO VALUES('"+isbn+"','"+bookName+"','"+auther+"','"+publisher+"','"+price+"','"+amount+"','"+typeld+"')";
stmt.close();
conn.close();
}else{
//如果fileitem中封装的是上传文件
//得到上传的文件名称,
String filename = item.getName();
System.out.println(filename);
request.getAttribute(filename);
if(filename==null || filename.trim().equals("")){
continue;
}
filename = filename.substring(filename.lastIndexOf("\\")+1);
InputStream in = item.getInputStream();
//得到文件保存的名称
String saveFilename = makeFileName(filename);
//得到文件的保存目录
String realSavePath = makePath(saveFilename, savePath);
//创建一个文件输出流
FileOutputStream out = new FileOutputStream(realSavePath + "\\" + saveFilename);
//创建一个缓冲区
byte buffer[] = new byte[1024];
//判断输入流中的数据是否已经读完的标识
int len = 0;
//循环将输入流读入到缓冲区当中,(len=in.read(buffer))>0就表示in里面还有数据
while((len=in.read(buffer))>0){
//使用FileOutputStream输出流将缓冲区的数据写入到指定的目录(savePath + "\\" + filename)当中
out.write(buffer, 0, len);
}
//关闭输入流
in.close();
//关闭输出流
out.close();
}
}
}catch (Exception e) {
// TODO: handle exception
}
request.getAttribute(getServletName());
request.getRequestDispatcher("/ShowBook.jsp").forward(request, response);
}
private String makeFileName(String filename){
//2.jpg
//为防止文件覆盖的现象发生,要为上传文件产生一个唯一的文件名
return UUID.randomUUID().toString() + "_" + filename;
}
private String makePath(String filename,String savePath){
//得到文件名的hashCode的值,得到的就是filename这个字符串对象在内存中的地址
int hashcode = filename.hashCode();
int dir1 = hashcode&0xf; //0--15
//构造新的保存目录
String dir = savePath + "\\" + dir1 ; //upload\2\3 upload\3\5
//File既可以代表文件也可以代表目录
File file = new File(dir);
//如果目录不存在
if(!file.exists()){
//创建目录
file.mkdirs();
}
return dir;
}
}
## 二、Jsp 的编写
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>文件上传</title>
</head>
<style>
body{
text-align:center}
.damo{
width: 180px;
}
</style>
<body>
<h3>新增图书</h3>
<hr>
<form action="AddBookServlet" enctype="multipart/form-data" method="post">
书 号:<input type="text" name="isbn"><br/>
书 名:<input type="text" name="bookName"><br/>
作 者:<input type="text" name="auther"><br/>
出版社:<input type="text" name="publisher"><br/>
单 价:<input type="text" name="price"><br/>
数 量:<input type="text" name="amount"><br/>
分 类:<input type="text" name="typeld"><br/>
封面图片:<input type="file" name="Photofile" class="damo"><br/>
<input type="submit" value="提交">
<input type="reset" value="重置">
</form>
</body>
</html>
三、显示图书信息
<%@page import="java.util.ArrayList"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="test10.Book" %>
<%@ page import="java.io.*" %>
<%@page import="java.sql.*" %>
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
body{
text-align:center
}
</style>
<meta charset="UTF-8">
<title>新增图书详情</title>
</head>
<body>
<h4>新增图书详情</h4>
<hr>
<%
request.setCharacterEncoding("UTF-8");
String isbn=request.getParameter("isbn");
Book book=(Book)request.getAttribute("book");
%>
<table>
<tr>
<td rowspan=6><img alt="" src="imges/<%=book.getPhoto() %>" width="200"></td>
<td>书 号:<%=book.getIsbn() %></td>
</tr>
<tr>
<td>书 名:<%=book.getBookName()%></td>
</tr>
<tr>
<td>作 者:<%=book.getAuther()%></td>
</tr>
<tr>
<td>出版社:<%=book.getPublisher()%></td>
</tr>
<tr>
<td>价 格:<%=book.getPrice()%></td>
</tr>
</table>
</body>
</html>
二、文件的下载
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* Created by lc on 2018/8/24.
*/
@WebServlet(name = "downServlet",urlPatterns = "/abc")
public class downServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
//获取文件名
String filename = request.getParameter("filename");
//文件所在的文件夹
String folder="abc/";
//通知浏览器以下载的方式打开
response.addHeader("Content-Type","application/octet-stream");
response.addHeader("Content-Disposition","attachment;filename="+filename);
//通过文件输入流读取文件
InputStream in=getServletContext().getResourceAsStream(folder+filename);
OutputStream out=response.getOutputStream();
byte[] bytes=new byte[1024];
int len=0;
while ((len=in.read(bytes))!=-1){
out.write(bytes,0,len);
}
}
}
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>文件下载</title>
</head>
<body>
<a href="/abc?filename=12.jpg">文件下载</a>
</body>