相關素材下載 01.jsp 文件上傳UploadServlet.java 文件下載DownloadServlet.java web.xml ...
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>