jsp+servlet实现文件上传下载

2019-08-16 10:29:27来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折

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>&nbsp;&nbsp;${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>

 


原文链接:https://www.cnblogs.com/yewen1234/p/11111666.html
如有疑问请与原作者联系

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:阿里java开发手册阅读心得

下一篇:Java - 格式化输出JSON字符串的两种方式