国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > JSP > 正文

JavaServlet的文件上傳和下載實現(xiàn)方法

2020-07-26 23:15:57
字體:
供稿:網(wǎng)友

先分析一下上傳文件的流程

1-先通過前段頁面中的選擇文件選擇要上傳的圖片

index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8" contentType="text/html; charset=UTF-8"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head>  <title>My JSP 'index.jsp' starting page</title>  <meta http-equiv="content-type" content="text/html;charset=utf-8">  <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">    <script type="text/javascript" src="js/jquery.min.js"></script>  <script type="text/javascript" src="js/common.js"></script>  <script type="text/javascript" src="js/ajaxfileupload.js"></script> </head> <body>  <input type="file" value="上傳" name="inputImage" id="inputImage">  <input type="button" value="上傳" id="upload">    <a id="downLoad">下載</a> </body></html>

2-點擊提交按鈕,通過ajax的文件上傳訪問服務(wù)器端

common.js  

var path = (function() { //獲取當(dāng)前網(wǎng)址 var curWwwPath = window.document.location.href; //獲取主機(jī)地址之后的目錄 var pathName = window.document.location.pathname; var pos = curWwwPath.indexOf(pathName); //獲取主機(jī)地址 var localhostPath = curWwwPath.substring(0, pos); //獲取帶"/"的項目名 var projectName = pathName.substring(0, pathName.substr(1).indexOf('/') + 1); return {   curWwwPath: curWwwPath,   pathName: pathName,   localhostPath: localhostPath,   projectName: projectName,   //部署路徑   deployPath: localhostPath + projectName  };})();
// 文件下載$("a[id=downLoad]").click(function(){ window.location.href=path.deployPath+"/fileDown";});// 文件上傳$("input[id=upload]").click(function() { $.ajaxFileUpload( {  url : path.deployPath + "/fileUp", // 處理頁面的絕對路徑  fileElementId : "inputImage", //file空間的id屬性  dataType : "json",  success : function(data) {   alert("上傳成功");  } });});

3-服務(wù)器端響應(yīng)保存或者下載

保存上傳文件的FileUpload.java

import java.io.File;import java.io.IOException;import java.io.PrintWriter;import java.util.ArrayList;import java.util.List;import java.util.UUID;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import net.sf.json.JSONArray;import org.apache.commons.fileupload.FileItem;import org.apache.commons.fileupload.FileUploadException;import org.apache.commons.fileupload.disk.DiskFileItemFactory;import org.apache.commons.fileupload.servlet.ServletFileUpload;import com.stu.util.HttpUtil;/** * 文件名稱: com.stu.fileupload.FileUpload.java<br/> * 初始作者: Administrator<br/> * 創(chuàng)建日期: 2018-1-31<br/> * 功能說明: 文件上傳 <br/> * =================================================<br/> * 修改記錄:<br/> * 修改作者 日期 修改內(nèi)容<br/> * ================================================<br/> * Copyright (c) 2010-2011 .All rights reserved.<br/> */public class FileUpload extends HttpServlet { private static final long serialVersionUID = 1L; @Override protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {  // 獲取到當(dāng)前服務(wù)器所在的路徑  String serverPath = req.getSession().getServletContext().getRealPath("/");  // 設(shè)置保存上傳文件的路徑  String saveDirPath = serverPath + "img";  File saveDirPathFileObj = new File(saveDirPath);  // 如果當(dāng)用來存放文件的目錄不存在時,要創(chuàng)建該目錄  if (!saveDirPathFileObj.exists()) {   saveDirPathFileObj.mkdirs();  }  // 創(chuàng)建一個解析器工廠  DiskFileItemFactory factory = new DiskFileItemFactory();  // 設(shè)置工廠的緩存區(qū)大小  factory.setSizeThreshold(5 * 1024);  // 文件上傳的解析器(文件上傳對象)  ServletFileUpload upload = new ServletFileUpload(factory);  // 設(shè)置上傳文件的最大值  upload.setSizeMax(3 * 1024 * 1024);  // 設(shè)置編碼格式  upload.setHeaderEncoding("UTF-8");  try {   // 上傳以后的文件名   List<String> uploadFileNames = new ArrayList<String>();   List<FileItem> fileItems = upload.parseRequest(req);   System.out.println(fileItems);   for (FileItem file : fileItems) {    // 新的文件名    String saveFileName = UUID.randomUUID().toString().replace("-", "");    // 文件的后綴    String oldFileName = new String(file.getName().getBytes(),    "UTF-8");    System.out.println("oldFileName" + oldFileName);    String fileType = oldFileName.substring(oldFileName.lastIndexOf("."));    // 新的文件路徑    String saveFilePath = saveDirPath + File.separator    + saveFileName + fileType;    uploadFileNames.add(saveFileName + fileType);    // 保存上傳的文件    file.write(new File(saveFilePath));   }   System.out.println(uploadFileNames);   HttpUtil.setAttribute(req, "urls", uploadFileNames);   res.setContentType("application/json;charset=utf-8");   PrintWriter pw = res.getWriter();   pw.print(JSONArray.fromObject(uploadFileNames));  } catch (FileUploadException e) {   e.printStackTrace();  } catch (Exception e) {   e.printStackTrace();  } }}

下載文件的FileDownload.java

import java.io.File;import java.io.IOException;import java.io.PrintWriter;import java.util.ArrayList;import java.util.List;import java.util.UUID;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import net.sf.json.JSONArray;import org.apache.commons.fileupload.FileItem;import org.apache.commons.fileupload.FileUploadException;import org.apache.commons.fileupload.disk.DiskFileItemFactory;import org.apache.commons.fileupload.servlet.ServletFileUpload;import com.stu.util.HttpUtil;/** * 文件名稱: com.stu.fileupload.FileUpload.java<br/> * 初始作者: Administrator<br/> * 創(chuàng)建日期: 2018-1-31<br/> * 功能說明: 文件上傳 <br/> * =================================================<br/> * 修改記錄:<br/> * 修改作者 日期 修改內(nèi)容<br/> * ================================================<br/> * Copyright (c) 2010-2011 .All rights reserved.<br/> */public class FileUpload extends HttpServlet { private static final long serialVersionUID = 1L; @Override protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {  // 獲取到當(dāng)前服務(wù)器所在的路徑  String serverPath = req.getSession().getServletContext().getRealPath("/");  // 設(shè)置保存上傳文件的路徑  String saveDirPath = serverPath + "img";  File saveDirPathFileObj = new File(saveDirPath);  // 如果當(dāng)用來存放文件的目錄不存在時,要創(chuàng)建該目錄  if (!saveDirPathFileObj.exists()) {   saveDirPathFileObj.mkdirs();  }  // 創(chuàng)建一個解析器工廠  DiskFileItemFactory factory = new DiskFileItemFactory();  // 設(shè)置工廠的緩存區(qū)大小  factory.setSizeThreshold(5 * 1024);  // 文件上傳的解析器(文件上傳對象)  ServletFileUpload upload = new ServletFileUpload(factory);  // 設(shè)置上傳文件的最大值  upload.setSizeMax(3 * 1024 * 1024);  // 設(shè)置編碼格式  upload.setHeaderEncoding("UTF-8");  try {   // 上傳以后的文件名   List<String> uploadFileNames = new ArrayList<String>();   List<FileItem> fileItems = upload.parseRequest(req);   System.out.println(fileItems);   for (FileItem file : fileItems) {    // 新的文件名    String saveFileName = UUID.randomUUID().toString().replace("-", "");    // 文件的后綴    String oldFileName = new String(file.getName().getBytes(),    "UTF-8");    System.out.println("oldFileName" + oldFileName);    String fileType = oldFileName.substring(oldFileName.lastIndexOf("."));    // 新的文件路徑    String saveFilePath = saveDirPath + File.separator    + saveFileName + fileType;    uploadFileNames.add(saveFileName + fileType);    // 保存上傳的文件    file.write(new File(saveFilePath));   }   System.out.println(uploadFileNames);   HttpUtil.setAttribute(req, "urls", uploadFileNames);   res.setContentType("application/json;charset=utf-8");   PrintWriter pw = res.getWriter();   pw.print(JSONArray.fromObject(uploadFileNames));  } catch (FileUploadException e) {   e.printStackTrace();  } catch (Exception e) {   e.printStackTrace();  } }}

這里面用到了一個HttpUtil類,代碼如下:

import javax.servlet.FilterConfig;import javax.servlet.ServletConfig;import javax.servlet.ServletContext;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpSession;/** * 文件名稱_com.niit.model2.util.Httputil.java</br> * 初始作逯ܿAdministrator</br> * 創(chuàng)建日期_2018-1-23</br> * 功能說明_這里用一句話描述這個類的作用--此句話需刪除 <br/> * =================================================<br/> * 修改記錄_br/> * 修改作

主站蜘蛛池模板:
兰州市|
清远市|
乐安县|
天气|
海口市|
镇平县|
丹江口市|
吴江市|
建宁县|
凌云县|
泸定县|
田林县|
丰县|
阿拉善盟|
闻喜县|
文山县|
德安县|
葫芦岛市|
历史|
崇左市|
库伦旗|
郴州市|
邮箱|
吉安市|
常宁市|
营山县|
都兰县|
长海县|
萝北县|
姜堰市|
绥德县|
和田县|
四川省|
凤山县|
通城县|
阜新|
无锡市|
安远县|
兖州市|
曲周县|
黑河市|