java檔案下載與上傳
阿新 • • 發佈:2018-12-06
package net.onerock.topic.utils; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; import org.springframework.web.multipart.support.StandardMultipartHttpServletRequest; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.net.URLEncoder; import java.text.SimpleDateFormat; import java.util.*; /** * @author LHW * @Description 操作檔案工具類 * @Date 2018年6月8日 上午11:42:44 * @Version v1.0 */ public class OperationFileUtil { private static OperationFileUtil instance; private OperationFileUtil() { super(); } public static OperationFileUtil getInstance() { if (instance == null) { synchronized (OperationFileUtil.class){ instance = new OperationFileUtil(); } } return instance; } /** * TODO:檔案下載 * * @param request * @param response * @param downFileName 下載時候的檔案的名字("下載.txt") * @param fileName 檔案的名字 ("demo.txt") * @param filePath 檔案的路徑 ("/opt/file") * @throws RuntimeException */ /** * * @param request * @param response * @param downFileName TODO:檔案下載後的名字 * @param fileName TODO:檔案的UUID * @param filePath TODO:檔案的路徑 * @throws Exception */ public void httpDownLoad(HttpServletRequest request, HttpServletResponse response,String downFileName, String fileName, String filePath) throws Exception { File file = new File(filePath + File.separator + fileName); if (!file.exists()) { throw new RuntimeException("檔案不存在"); } InputStream inStream = new FileInputStream(filePath + File.separator + fileName);// 檔案的存放路徑 // 設定輸出的格式 response.reset(); response.setContentType("application/octet-stream"); /* if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) { //ie fileName = URLEncoder.encode(fileName, "UTF-8"); } else { //其它瀏覽器 fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1"); } */ downFileName = URLEncoder.encode(downFileName, "UTF-8"); response.addHeader("Content-Disposition", "attachment;filename=" + downFileName); // 迴圈取出流中的資料 byte[] b = new byte[100]; int len; while ((len = inStream.read(b)) > 0) { response.getOutputStream().write(b, 0, len); } inStream.close(); } /** * 檔案上傳OFD * * @param path * @param file * @return */ public Map<String, Object> uploadOFD(String path, MultipartFile file) { Map<String, Object> map = new HashMap<String, Object>(); SimpleDateFormat dateformat1 = new SimpleDateFormat("yyyyMMddHHmmss"); try { String fileName = file.getOriginalFilename(); String prefix = fileName.substring(fileName.lastIndexOf(".") + 1); String uuidName = Identities.uuid() + dateformat1.format(new Date()) + "." + prefix; File dir = new File(path, uuidName); if (!dir.exists()) { dir.mkdirs(); } // MultipartFile自帶的解析方法 file.transferTo(dir); String filePath = path + File.separator + uuidName; File f = new File(filePath); if (f.exists()) { map.put("status", true); map.put("name", fileName); map.put("path", path); map.put("uuidname", uuidName); } else { map.put("status", false); } } catch (Exception e) { System.out.println("**********************OFD檔案上傳失敗!**********************"); e.printStackTrace(); } return map; } //返回值 :list物件,包含內容依次為 //1.上傳是否成功(0代表檔案上傳失敗,1代表檔案上傳成功) //2.檔名 //3.已上傳檔案大小 public List<String> uploadMethod(HttpServletRequest request, HttpServletResponse response, String tempFilePath, String realFilePath, String realFileName) throws Exception { List<String> ret = new ArrayList(); try { long now = System.currentTimeMillis(); //根據系統時間生成上傳夠儲存的檔名 String prefix = String.valueOf(now); //設定長傳檔案的最大值:200MB final long MAX_SIZE = 200 * 1024 * 1024; response.setContentType("text/html"); //字元編碼為UTF-8 response.setCharacterEncoding("UTF-8"); //例項化一個硬碟檔案工廠,用來配置檔案組建ServletFileUpload DiskFileItemFactory factory = new DiskFileItemFactory(); //設定長傳檔案時用於臨時存放檔案的記憶體大小,這裡是4K,多餘的部分將臨時存在硬碟 factory.setSizeThreshold(4096); //設定存放臨時檔案的目錄,web根目錄下的UploadTemp目錄 //factory.setRepository(new File(request.getRealPath("/")+ "UploadTemp")); System.out.println("寫入檔案:" + tempFilePath); factory.setRepository(new File(tempFilePath)); /** * 用以上工廠例項化長傳元件 */ ServletFileUpload sfu = new ServletFileUpload(factory); //設定最大上傳尺寸 sfu.setSizeMax(MAX_SIZE); PrintWriter out = response.getWriter(); //從request得到 所有 上傳域的列表 List<FileItem> fileList = null; try { fileList = sfu.parseRequest(request); } catch (Exception e) { System.out.println("========================================="); e.printStackTrace(); System.out.println("========================================="); try { int bytesum = 0; int byteread = 0; String tempName = "temp.txt";//factory.getTempFileName(); // MkDirData.getInstance().createMkdir(tempFilePath); String oldPath = tempFilePath + "/" + tempName; //String oldPath = request.getRealPath("/") + "UploadTemp"+ "/" + tempFileName; System.out.println("建立檔案目錄:" + realFilePath); // MkDirData.getInstance().createMkdir(realFilePath); String newPath = realFilePath + "/" + tempName; //String newPath = request.getRealPath("/") + "/UploadFile/"+ tempFileName; File oldfile = new File(oldPath); if (oldfile.exists()) { //檔案存在時 InputStream inStream = new FileInputStream(oldPath); //讀入原檔案 FileOutputStream fs = new FileOutputStream(newPath); System.out.println("寫入新檔案:" + newPath); byte[] buffer = new byte[4444]; int length; while ((byteread = inStream.read(buffer)) != -1) { bytesum += byteread; //位元組數 檔案大小 fs.write(buffer, 0, byteread); } inStream.close(); fs.close(); //System.out.println("檔案大小="+oldfile.length()); ret.add("0"); ret.add(tempName); ret.add(oldfile.length() + ""); return ret; } } catch (Exception ex) { System.out.println("複製temp檔案操作出錯"); System.out.println("========================================="); ex.printStackTrace(); System.out.println("========================================="); ret.add("0"); ret.add(null); ret.add(null); return ret; } System.out.println("e.getMessage=" + e.getMessage()); } //得到所有上傳的檔案 Iterator fileItr = null; if (fileList != null) { fileItr = fileList.iterator(); } long size = 0; // 迴圈處理所有檔案 while (fileItr != null && fileItr.hasNext()) { FileItem fileItem = null; String path = ""; // 獲取當前檔案 // 獲取當前檔案 Object obj = fileItr.next(); if (obj != null && obj instanceof FileItem) { fileItem = (FileItem) obj; } else { continue; } // 忽略簡單form欄位 而不是 上傳域的檔案域(<input type="text" />等) if (fileItem == null || fileItem.isFormField()) { continue; } // 獲取檔案的完整路徑 path = fileItem.getName(); //System.out.println("path="+path); // 獲取檔案大小 size = fileItem.getSize(); //System.out.println("size="+size); // 得到去除路徑的檔名 String realName = path.substring(path.lastIndexOf("\\") + 1); //System.out.println("realName="+realName); // 得到檔案的拓展名(無拓展名時將得到全名) String extName = realName .substring(realName.lastIndexOf(".") + 1); // 儲存的最終檔案完整路徑,儲存在web根目錄下的UploadFile目錄下 //String finalName = request.getRealPath("/") + "/UploadFile/"+ prefix + "." + extName; String finalName = realFilePath + "/" + realFileName; //System.out.println("finalName="+finalName); try { // 儲存檔案 fileItem.write(new File(finalName)); } catch (Exception e) { //System.out.println(e.getMessage()); } } ret.add("1"); ret.add(realFileName); ret.add(size + ""); return ret; } catch (Exception ex) { ex.printStackTrace(); ret.add("0"); ret.add(""); ret.add("0"); return ret; } } }