zoukankan      html  css  js  c++  java
  • servlet实现图片预览、文件上传下载(转载)

    //文件上传
    package com.imooc.servlet;
    
    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 {
    
        public void doGet(HttpServletRequest req, HttpServletResponse resp)
                throws ServletException, IOException {
            doPost(req,resp);
        }
    
        public void doPost(HttpServletRequest req, HttpServletResponse resp)
                throws ServletException, IOException {
            //从request当中获取流信息
            InputStream fileSource = req.getInputStream();
            String tempFileName = "E:/tempFile";
            //tempFile指向临时文件
            File tempFile = new File(tempFileName);
            //outputStram文件输出流指向这个临时文件
            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("\") + 1;
            int endIndex = str.lastIndexOf(""");
            String filename = str.substring(beginIndex, endIndex);
            System.out.println("filename:" + filename);
    
            //重新定位文件指针到文件头
            randomFile.seek(0);
            long startPosition = 0;
            int i = 1;
            //获取文件内容 开始位置
            while(( n = randomFile.readByte()) != -1 && i <=4){
                if(n == '
    '){
                    startPosition = randomFile.getFilePointer();
                    i ++;
                }
            }
            startPosition = randomFile.getFilePointer() -1;
            //获取文件内容 结束位置
            randomFile.seek(randomFile.length());
            long endPosition = randomFile.getFilePointer();
            int j = 1;
            while(endPosition >=0 && j<=2){
                endPosition--;
                randomFile.seek(endPosition);
                if(randomFile.readByte() == '
    '){
                    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);
            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);
        }
    }
    

      

    //文件下载
    package com.imooc.servlet;
    
    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 {
    
        public 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 ouputStream = resp.getOutputStream();
                byte b[] = new byte[1024];
                int n ;
                while((n = inputStream.read(b)) != -1){
                    ouputStream.write(b,0,n);
                }
                //关闭流、释放资源
                ouputStream.close();
                inputStream.close();
    
    
            }else{
                req.setAttribute("errorResult", "文件不存在下载失败!");
                RequestDispatcher dispatcher = req.getRequestDispatcher("jsp/01.jsp");
                dispatcher.forward(req, resp);
            }
    
    
        }
    
        public void doPost(HttpServletRequest req, HttpServletResponse resp)
                throws ServletException, IOException {
            doGet(req,resp);
        }
    
    }
    jsp页面
    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    <%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
    %>
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
        <base href="<%=basePath%>">
    
        <title>My JSP '01.jsp' starting page</title>
    
        <meta http-equiv="pragma" content="no-cache">
        <meta http-equiv="cache-control" content="no-cache">
        <meta http-equiv="expires" content="0">    
        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
        <meta http-equiv="description" content="This is my page">
        <link rel="stylesheet" type="text/css" href="css/common.css" />
        <script type="text/javascript" src="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:///" + $("#myfile").val());
                });
    
                var la = $("#large");
                la.hide();
    
                $("#previewImg").mousemove(function(e){
                    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;
                document.getElementById("previewImg").innerHTML = 
                    "<img src = '" + str + "' />";
            }
            */
        </script>
      </head>
    
      <body>
    
         <img id="previewImg" src="images/preview.jpg" width="80" height="80" />
         <form action="uploadServlet.do" method="post" enctype="multipart/form-data">
            请选择图片:<input id="myfile" name="myfile" type="file" onchange="showPreview(this)"/>
            <input type="submit" value="提交"  />${result}
        </form>
        下载:<a href="downloadServlet.do?filename=test.txt">test.txt</a>    ${errorResult}
    
        <div id="large"></div>
    
        <hr>
        <h2>图片预览</h2>
        <p><img id="largeImg" src="images/img1-lg.jpg" alt="Large Image"/></p>
        <p class="thumbs">
            <a href="images/img2-lg.jpg" title="Image2"><img src="images/img2-thumb.jpg"></a>
            <a href="images/img3-lg.jpg" title="Image3"><img src="images/img3-thumb.jpg"></a>
            <a href="images/img4-lg.jpg" title="Image4"><img src="images/img4-thumb.jpg"></a>
            <a href="images/img5-lg.jpg" title="Image5"><img src="images/img5-thumb.jpg"></a>
            <a href="images/img6-lg.jpg" title="Image6"><img src="images/img6-thumb.jpg"></a>
        </p>
      </body>
    </html>  

    慕课网《easy实现文件上传下载(David)》视频教程;http://www.imooc.com/video/5566

    下篇就发布在FastDfs上实现图片上传下载的Demo

  • 相关阅读:
    使用ExpandableListView——当有Group选项展开时,如何正确获取长按的Group选项。
    Android 如何全局获取Context
    Android记录11-控制ExpandableListView展开和关闭
    setOnKeyListener响应两次问题
    ExpandableListView方法详解
    Leetcode 75 Sort Colors
    Leetcode 48 Rotate Image
    Leetcode 64 Minimum Path Sum
    Leetcode 268 Missing Number
    Leetcode 39 40 216 Combination Sum I II III
  • 原文地址:https://www.cnblogs.com/victory8023/p/5544973.html
Copyright © 2011-2022 走看看