文件的上傳與下載(2)
阿新 • • 發佈:2018-08-30
let ntb nco 設置 路徑 gif exception nds 註釋
文件的上傳與下載
1、文件的上傳
1.1、前端代碼:
1 <form action="${pageContext.request.contextPath}/upload.do" enctype="multipart/form-data" method="post">
2 上傳文件1:<input type="file" name="file1"></br>
3 上傳文件2:<input type="file" name="file2"></br>
4 上傳文件3:<input type="file" name="file3" ></br>
5 <input type="submit" value="提交"/>${result}
6 </form>
其中關於enctype的用法。
application/x-www-form-urlencoded不是不能上傳文件,是只能上傳文本格式的文件,multipart/form-data是將文件以二進制的形式上傳,這樣可以實現多種類型的文件上傳
1.2、後端代碼
web.xml代碼:
1 <servlet>
2 <servlet-name>UploadServlet</servlet-name>
3 <servlet-class>uploadServlet.UploadServlet2</servlet-class>
4 </servlet>
5 <servlet-mapping>
6 <servlet-name>UploadServlet</servlet-name>
7 <url-pattern>/upload.do</url-pattern>
8 </servlet-mapping>
servlet代碼:
1 public class UploadServlet2 extends HttpServlet {
2
3 @Override
4 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
5 //super.doGet(req, resp);
6 doPost(req,resp);
7 }
8
9 @Override
10 protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
11 /**設置上傳保存路徑*/
12 String filePath = getServletContext().getRealPath("/")+"images";
13 File file = new File(filePath);
14 if (!file.exists()){
15 file.mkdir();
16 }
17 SmartUpload smartUpload = new SmartUpload();
18 /**初始化對象*/
19 smartUpload.initialize(getServletConfig(),req,resp);
20 /**設置上傳文件大小*/
21 smartUpload.setMaxFileSize(1024*1024*100);
22 /**設置所有文件的大小*/
23 smartUpload.setTotalMaxFileSize(1024*1024*1000);
24 /**設置允許上傳文件的類型*/
25 smartUpload.setAllowedFilesList("txt,jpg,png,gif");
26 String result = "上傳成功";
27 try {
28 smartUpload.setDeniedFilesList("rar,jsp,js");
29 smartUpload.upload();
30 int count = smartUpload.save(filePath);
31 System.out.println("上傳成功了:"+count+"文件");
32 } catch (Exception e) {
33 result = "上傳失敗";
34 e.printStackTrace();
35 }
36
37 req.setAttribute("result",result);
38 req.getRequestDispatcher("/index.jsp").forward(req,resp);
39
40 }
41 }
2、文件的下載
2.1 前端代碼
註意:發送的是一個get請求
下載:<a href="${pageContext.request.contextPath}/download.do?filename=01.mp4">下載</a>
2.2 servlet代碼
註意如果發送的是一個GET請求,一定要將super.doGet(req,resp);方法註釋掉;
否則會報錯HTTP Status 405 - HTTP method GET is not supported by this URL。
原因是父類中返回的信息(查看原碼可知)。
1 /**
2 * @Author: jack
3 * @Create: 2018-08-29-16:25
4 * @Desc:
5 **/
6 public class UploadServlet3 extends HttpServlet {
7
8 @Override
9 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
10 // super.doGet(req, resp);
11 doPost(req,resp);
12
13 }
14
15 @Override
16 protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
17 /**獲取文件名*/
18 String filename = req.getParameter("filename");
19 /**初始化對象*/
20 SmartUpload su = new SmartUpload();
21 su.initialize(getServletConfig(),req,resp);
22 /**設定contentDisposition為null以禁止瀏覽器自動打開文件*/
23 su.setContentDisposition(null);
24 try {
25 /**文件在服務器的地址*/
26 su.downloadFile("/images/"+filename);
27 } catch (SmartUploadException e) {
28 e.printStackTrace();
29 }
30 }
31 }
3、服務器向瀏覽器發送文件
3.1 前端代碼
1 <img id="img" src="">
2 <button onclick="showImg()">顯示</button>
3 <button onclick="coverImg()">隱藏</button><br/>
4
5 <script>
6 /**顯示圖片*/
7 function showImg() {
8 var img = document.getElementById("img");
9 img.setAttribute("src","/image");
10
11 }
12 /**隱藏圖片*/
13 function coverImg() {
14 var img = document.getElementById("img");
15 img.setAttribute("src","");
16 }
17 </script>
3.2 java後臺代碼
1 **
2 * 服務器向瀏覽器發送圖片流
3 * @param response
4 * @throws IOException
5 */
6 @RequestMapping("/image")
7 public void demo(HttpServletResponse response) throws IOException {
8 /**設置編碼格式*/
9 response.setContentType("charset=utf-8");
10 /**文件所在的位置*/
11 File file = new File("F:/temp/1.jpg");
12 FileInputStream in = new FileInputStream(file);
13 /**創建輸出流向網頁輸入內容*/
14 OutputStream out = response.getOutputStream();
15 byte[] buffer = new byte[1024];
16 int len;
17 while ((len=in.read(buffer)) > 0){
18 out.write(buffer,0,len);
19 }
20 /**關閉流*/
21 in.close();
22
23 }
文件的上傳與下載(2)