java 檔案上傳下載刪除
阿新 • • 發佈:2018-11-19
適用於springboot,ssm框架等
// ============檔案刪除=============== @RequestMapping(value = "/deleteFile", method = RequestMethod.GET) @ResponseBody public void deleteFile(Long fileId) { File fileVal = fileService.selectId(fileId); fileService.deleteId(fileId); //刪除資料庫 java.io.File file = new java.io.File(fileVal.getUrl()); boolean exis = file.exists(); // 判斷目錄或檔案是否存在 boolean isex = file.isFile(); // 判斷是否為檔案 file.delete(); //刪除檔案 }
上傳檔案方法,適用於多,單檔案上傳
// ============controller方法=============== @RequestMapping(value = "/fileUpdateImg", method = RequestMethod.POST) @ResponseBody public String handleFileUpload1(HttpServletRequest request) throws IOException { List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file"); //接收到的檔案 String filePath = "file/img/"; //上傳路徑 List<Map<String, String>> list = utlisFile.handleFileUpload(files, filePath); //檔案上傳 return "yes"; } // ============工具類( utlisFile ) 方法=============== /* * * @Description //TODO 檔案上傳 * @Date 2018/10/8/008/ * @Param [files, filepath] * @return java.util.List<java.util.Map<java.lang.String,java.lang.String>> **/ public static List<Map<String, String>> handleFileUpload(List<MultipartFile> files, String filepath) throws IOException { List<Map<String, String>> listfile = new ArrayList(); MultipartFile file = null; BufferedOutputStream stream = null; for (int i = 0; i < files.size(); ++i) { file = files.get(i); if (!file.isEmpty()) { try { //上傳路徑 String uploadFilePath = file.getOriginalFilename(); String uploadFileName = uploadFilePath.substring(uploadFilePath.lastIndexOf('\\') + 1,uploadFilePath.indexOf('.')); String uploadFileSuffix = uploadFilePath.substring(uploadFilePath.indexOf('.') + 1, uploadFilePath.length()); //獲取跟目錄 File path = new File(ResourceUtils.getURL("classpath:").getPath()); if (!path.exists()) path = new File(""); File upload = new File(path.getAbsolutePath(), filepath); if (!upload.exists()) upload.mkdirs(); System.out.println(upload); String datess = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()); String pathfile = upload + "\\" + uploadFileName + datess + "." + uploadFileSuffix; System.out.println(pathfile); stream = new BufferedOutputStream(new FileOutputStream(new File(pathfile))); stream = new BufferedOutputStream(new FileOutputStream(new File(pathfile))); byte[] bytes = file.getBytes(); stream.write(bytes, 0, bytes.length); } catch (IOException e) { e.printStackTrace(); } finally { if (stream != null) { stream.close(); } } } } return listfile; }
檔案下載,自行傳檔案路徑,工具類 utlisFile 方法
/** * @return * @Description //TODO 檔案下載 * @Date 2018/10/8/008/ * @Param **/ public static void excelxiazan(HttpServletResponse res, String fileName) throws UnsupportedEncodingException { //要下載的檔案路徑(前臺傳id) //String fileName = excelService.selectbyId(eid); //檔案命名(獲得完整路徑最後的 \\ 後的內容) int fileXs = fileName.lastIndexOf("\\"); //下載檔名,去掉時時間戳 String fileXsl = fileName.substring(fileXs + 1, fileName.length() - 18); //String fileXsl = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()); //資訊頭: 會告訴瀏覽器這個檔案的名字和型別(必須設定) res.setHeader("content-type", "application/octet-stream"); res.setContentType("application/octet-stream"); //Content-Disposition : 指定的型別是檔案的副檔名(也就是下載檔案的名字) //下載名亂碼解決 --> java.net.URLEncoder.encode(fileXsl, "UTF-8") res.setHeader("Content-Disposition", "attachment; filename=" + java.net.URLEncoder.encode(fileXsl + ".xls", "UTF-8")); byte[] buff = new byte[1024]; BufferedInputStream bis = null; OutputStream os = null; try { os = res.getOutputStream(); bis = new BufferedInputStream(new FileInputStream(new File(fileName))); int i = bis.read(buff); while (i != -1) { os.write(buff, 0, buff.length); os.flush(); i = bis.read(buff); } } catch (IOException e) { e.printStackTrace(); } finally { if (bis != null) { try { bis.close(); } catch (IOException e) { e.printStackTrace(); } } } }
多檔案壓縮下載
//========================== TODO (方法)多檔案下載ZIP包 ========================
/* *
* 需要 filePaths 下載路徑集
* zipNamex 壓縮包名+ .zip
* res HttpServletResponse
**/
public void exceDownload(List<String> filePaths, HttpServletResponse res, String zipNamex) throws
IOException {
String zipName = zipNamex; //壓縮包名字
res.setContentType("text/html; charset=UTF-8"); //設定編碼字元
res.setContentType("application/octet-stream"); //設定內容型別為下載型別
OutputStream out = res.getOutputStream(); //建立頁面返回方式為輸出流,會自動彈出下載框
File path = new File(ResourceUtils.getURL("classpath:").getPath()); //專案跟目錄
if (!path.exists()) path = new File("");
File upload = new File(path.getAbsolutePath(), "static/images/uploaZip"); //壓縮包根目錄
if (!upload.exists()) upload.mkdirs();
String zipFilePath = upload + File.separator + zipName; //拼接目錄
//建立zip檔案輸出流 == 壓縮檔案========================================================
File zip = new File(zipFilePath);
if (!zip.exists()) {
zip.createNewFile();
}
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zip));
//打壓縮包
this.zipFile(String.valueOf(upload), zipName, zipFilePath, filePaths, zos);
zos.close(); //設定下載的壓縮檔名稱
res.setHeader("Content-disposition", "attachment;filename=" + java.net.URLEncoder.encode(zipName, "UTF-8"));
//建立zip檔案輸出流==========================================================
//將打包後的檔案寫到客戶端,輸出的方法同上,使用緩衝流輸出
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(zipFilePath));
byte[] buff = new byte[bis.available()];
bis.read(buff);
bis.close();
out.write(buff);//輸出資料檔案
out.flush();//釋放快取
out.close();//關閉輸出流
}
/**
* //TODO 壓縮檔案
*
* @param zipBasePath 臨時壓縮檔案基礎路徑
* @param zipName 臨時壓縮檔名稱
* @param zipFilePath 臨時壓縮檔案完整路徑
* @param filePaths 需要壓縮的檔案路徑集合
* @throws IOException
*/
public static String zipFile(String zipBasePath, String zipName, String
zipFilePath, List<String> filePaths, ZipOutputStream zos) throws IOException {
//迴圈讀取檔案路徑集合,獲取每一個檔案的路徑
for (String filePath : filePaths) {
File inputFile = new File(filePath); //根據檔案路徑建立檔案
if (inputFile.exists()) { //判斷檔案是否存在
if (inputFile.isFile()) { //判斷是否屬於檔案,還是資料夾
//建立輸入流讀取檔案
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(inputFile));
//將檔案寫入zip內,即將檔案進行打包
zos.putNextEntry(new ZipEntry(inputFile.getName()));
//寫入檔案的方法,同上
int size = 0;
byte[] buffer = new byte[1024]; //設定讀取資料快取大小
while ((size = bis.read(buffer)) > 0) {
zos.write(buffer, 0, size);
}
//關閉輸入輸出流
zos.closeEntry();
bis.close();
} else { //如果是資料夾,則使用窮舉的方法獲取檔案,寫入zip
try {
File[] files = inputFile.listFiles();
List<String> filePathsTem = new ArrayList<String>();
for (File fileTem : files) {
filePathsTem.add(fileTem.toString());
}
return zipFile(zipBasePath, zipName, zipFilePath, filePathsTem, zos);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
return null;
}
單檔案上傳
/*========================== 單檔案上傳 =============================== */
@ResponseBody
@RequestMapping(value = "/testUploadFile", method = RequestMethod.POST)
public String testUploadFile(HttpServletRequest req,
MultipartHttpServletRequest multiReq) {
// 獲取上傳檔案的路徑
String uploadFilePath = multiReq.getFile("file").getOriginalFilename();
System.out.println("uploadFlePath:" + uploadFilePath);
// 擷取上傳檔案的檔名
String uploadFileName = uploadFilePath.substring(
uploadFilePath.lastIndexOf('\\') + 1, uploadFilePath.indexOf('.'));
System.out.println("multiReq.getFile()" + uploadFileName);
// 擷取上傳檔案的字尾
String uploadFileSuffix = uploadFilePath.substring(
uploadFilePath.indexOf('.') + 1, uploadFilePath.length());
System.out.println("uploadFileSuffix:" + uploadFileSuffix);
FileOutputStream fos = null;
FileInputStream fis = null;
try {
fis = (FileInputStream) multiReq.getFile("file").getInputStream();
//獲取跟目錄
File path = new File(ResourceUtils.getURL("classpath:").getPath());
if (!path.exists()) path = new File("");
System.out.println("path:" + path.getAbsolutePath());
//如果上傳目錄為/static/images/upload/,則可以如下獲取:
File upload = new File(path.getAbsolutePath(), "static/images/upload/");
if (!upload.exists()) upload.mkdirs();
System.out.println("upload url:" + upload.getAbsolutePath());
//在開發測試模式時,得到的地址為:{專案跟目錄}/target/static/images/upload/
//在打包成jar正式釋出時,得到的地址為:{釋出jar包目錄}/static/images/upload/
fos = new FileOutputStream(upload + "/" + uploadFileName + "." + uploadFileSuffix);
byte[] temp = new byte[1024];
int i = fis.read(temp);
while (i != -1) {
fos.write(temp, 0, temp.length);
fos.flush();
i = fis.read(temp);
}
return "上傳成功";
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fis != null) {
fis.close();
}
if (fos != null) {
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return "上傳失敗";
}