码迷,mamicode.com
首页 > Web开发 > 详细

慕课网文件上传

时间:2016-04-19 00:15:12      阅读:491      评论:0      收藏:0      [点我收藏+]

标签:

  servlet方式上传:

UploadServlet.java 
 1 package com.imooc.servlet;
 2 
 3 import java.io.File;
 4 import java.io.FileOutputStream;
 5 import java.io.IOException;
 6 import java.io.InputStream;
 7 import java.io.RandomAccessFile;
 8 
 9 import javax.servlet.RequestDispatcher;
10 import javax.servlet.ServletException;
11 import javax.servlet.http.HttpServlet;
12 import javax.servlet.http.HttpServletRequest;
13 import javax.servlet.http.HttpServletResponse;
14 
15 public class UploadServlet extends HttpServlet {
16 
17     public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
18         doPost(req, resp);
19     }
20 
21     public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
22         // 从request当中获取流信息
23         InputStream fileSource = req.getInputStream();
24         String tempFileName = "E:/tempFile";
25         // tempFile指向临时文件
26         File tempFile = new File(tempFileName);
27         // outputStram文件输出流指向这个临时文件
28         FileOutputStream outputStream = new FileOutputStream(tempFile);
29         byte b[] = new byte[1024];
30         int n;
31         while ((n = fileSource.read(b)) != -1) {
32             outputStream.write(b, 0, n);
33         }
34         // 关闭输出流、输入流
35         outputStream.close();
36         fileSource.close();
37 
38         // 获取上传文件的名称
39         RandomAccessFile randomFile = new RandomAccessFile(tempFile, "r");
40         randomFile.readLine();
41         String str = randomFile.readLine();
42         int beginIndex = str.lastIndexOf("\\") + 1;
43         int endIndex = str.lastIndexOf("\"");
44         String filename = str.substring(beginIndex, endIndex);
45         System.out.println("filename:" + filename);
46 
47         // 重新定位文件指针到文件头
48         randomFile.seek(0);
49         long startPosition = 0;
50         int i = 1;
51         // 获取文件内容 开始位置
52         while ((n = randomFile.readByte()) != -1 && i <= 4) {
53             if (n == ‘\n‘) {
54                 startPosition = randomFile.getFilePointer();
55                 i++;
56             }
57         }
58         startPosition = randomFile.getFilePointer() - 1;
59         // 获取文件内容 结束位置
60         randomFile.seek(randomFile.length());
61         long endPosition = randomFile.getFilePointer();
62         int j = 1;
63         while (endPosition >= 0 && j <= 2) {
64             endPosition--;
65             randomFile.seek(endPosition);
66             if (randomFile.readByte() == ‘\n‘) {
67                 j++;
68             }
69         }
70         endPosition = endPosition - 1;
71 
72         // 设置保存上传文件的路径
73         String realPath = getServletContext().getRealPath("/") + "images";
74         File fileupload = new File(realPath);
75         if (!fileupload.exists()) {
76             fileupload.mkdir();
77         }
78         File saveFile = new File(realPath, filename);
79         RandomAccessFile randomAccessFile = new RandomAccessFile(saveFile, "rw");
80         // 从临时文件当中读取文件内容(根据起止位置获取)
81         randomFile.seek(startPosition);
82         while (startPosition < endPosition) {
83             randomAccessFile.write(randomFile.readByte());
84             startPosition = randomFile.getFilePointer();
85         }
86         // 关闭输入输出流、删除临时文件
87         randomAccessFile.close();
88         randomFile.close();
89         tempFile.delete();
90 
91         req.setAttribute("result", "上传成功!");
92         RequestDispatcher dispatcher = req.getRequestDispatcher("jsp/01.jsp");
93         dispatcher.forward(req, resp);
94     }
95 }

 

DownloadServlet.java
 1 package com.imooc.servlet;
 2 
 3 import java.io.File;
 4 import java.io.FileInputStream;
 5 import java.io.IOException;
 6 import java.io.InputStream;
 7 
 8 import javax.servlet.RequestDispatcher;
 9 import javax.servlet.ServletException;
10 import javax.servlet.ServletOutputStream;
11 import javax.servlet.http.HttpServlet;
12 import javax.servlet.http.HttpServletRequest;
13 import javax.servlet.http.HttpServletResponse;
14 
15 public class DownloadServlet extends HttpServlet {
16 
17     public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
18         // 获取文件下载路径
19         String path = getServletContext().getRealPath("/") + "images/";
20         String filename = req.getParameter("filename");
21         File file = new File(path + filename);
22         if (file.exists()) {
23             // 设置相应类型application/octet-stream
24             resp.setContentType("application/x-msdownload");
25             // 设置头信息
26             resp.setHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");
27             InputStream inputStream = new FileInputStream(file);
28             ServletOutputStream ouputStream = resp.getOutputStream();
29             byte b[] = new byte[1024];
30             int n;
31             while ((n = inputStream.read(b)) != -1) {
32                 ouputStream.write(b, 0, n);
33             }
34             // 关闭流、释放资源
35             ouputStream.close();
36             inputStream.close();
37 
38         } else {
39             req.setAttribute("errorResult", "文件不存在下载失败!");
40             RequestDispatcher dispatcher = req.getRequestDispatcher("jsp/01.jsp");
41             dispatcher.forward(req, resp);
42         }
43 
44     }
45 
46     public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
47         doGet(req, resp);
48     }
49 
50 }

 jsp:

 

 1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
 2 <%
 3 String path = request.getContextPath();
 4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
 5 %>
 6 
 7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 8 <html>
 9   <head>
10     <base href="<%=basePath%>">
11     
12     <title>My JSP ‘01.jsp‘ starting page</title>
13     
14     <meta http-equiv="pragma" content="no-cache">
15     <meta http-equiv="cache-control" content="no-cache">
16     <meta http-equiv="expires" content="0">    
17     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
18     <meta http-equiv="description" content="This is my page">
19     <link rel="stylesheet" type="text/css" href="css/common.css" />
20     <script type="text/javascript" src="js/jquery-1.11.1.js"></script>
21     <script type="text/javascript">
22         $(function(){
23             $(".thumbs a").click(function(){
24                 var largePath  = $(this).attr("href");
25                 var largeAlt = $(this).attr("title");
26                 $("#largeImg").attr({
27                     src : largePath,
28                     alt : largeAlt
29                 });
30                 return false;
31             });
32             
33             $("#myfile").change(function(){
34                 $("#previewImg").attr("src","file:///" + $("#myfile").val());
35             });
36             
37             var la = $("#large");
38             la.hide();
39             
40             $("#previewImg").mousemove(function(e){
41                 la.css({
42                     top : e.pageY,
43                     left : e.pageX
44                 }).html(<img src = " + this.src + " />).show();
45             }).mouseout(function(){
46                 la.hide();
47             });
48         });    
49         /*  //使用js实现文件上传图片的预览
50         function showPreview(obj){
51             var str = obj.value;
52             document.getElementById("previewImg").innerHTML = 
53                 "<img src = ‘" + str + "‘ />";
54         }
55         */
56         function showPreview(obj){
57             var str = obj.value;
58             document.getElementById("previewImg").innerHTML = 
59                 "<img src = ‘" + str + "‘ />";
60         }
61     </script>
62   </head>
63   
64   <body>
65 
66        <img id="previewImg" src="images/preview.jpg" width="80" height="80" />
67        <form action="uploadServlet.do" method="post" enctype="multipart/form-data">
68           请选择图片:<input id="myfile" name="myfile" type="file" onchange="showPreview(this)"/>
69           <input type="submit" value="提交"  />${result}
70       </form>
71       下载:<a href="downloadServlet.do?filename=test1.txt">test1.txt</a> &nbsp;&nbsp; ${errorResult}
72       
73       <div id="large"></div>
74       
75       <hr>
76     <h2>图片预览</h2>
77     <p><img id="largeImg" src="images/img1-lg.jpg" alt="Large Image"/></p>
78     <p class="thumbs">
79         <a href="images/img2-lg.jpg" title="Image2"><img src="images/img2-thumb.jpg"></a>
80         <a href="images/img3-lg.jpg" title="Image3"><img src="images/img3-thumb.jpg"></a>
81         <a href="images/img4-lg.jpg" title="Image4"><img src="images/img4-thumb.jpg"></a>
82         <a href="images/img5-lg.jpg" title="Image5"><img src="images/img5-thumb.jpg"></a>
83         <a href="images/img6-lg.jpg" title="Image6"><img src="images/img6-thumb.jpg"></a>
84     </p>
85   </body>
86 </html>

项目目录技术分享

慕课网文件上传

标签:

原文地址:http://www.cnblogs.com/Sunnor/p/5406413.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!