Java上傳下載檔案並實現加密解密
阿新 • • 發佈:2020-04-14
使用 Jersey 伺服器實現上傳,使用 HTTP 請求實現下載
引入依賴
在 pom.xml 中新增 Jersey 相關依賴
<dependency> <groupId>com.sun.jersey</groupId> <artifactId>jersey-client</artifactId> <version>1.18.1</version> </dependency>
建立工具類
import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientHandlerException; import com.sun.jersey.api.client.UniformInterfaceException; import com.sun.jersey.api.client.WebResource; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest; import java.io.*; import java.net.HttpURLConnection; import java.net.URL; import java.util.UUID; public class FileUtils { // 加密/解密檔案的金鑰 public static final int CRYPTO_SECRET_KEY = 0x99; public static int FILE_DATA = 0; /** * 加密/解密 檔案 * @param srcFile 原檔案 * @param encFile 加密/解密後的檔案 * @throws Exception */ public static void cryptoFile(File srcFile,File encFile) throws Exception { InputStream inputStream = new FileInputStream(srcFile); OutputStream outputStream = new FileOutputStream(encFile); while ((FILE_DATA = inputStream.read()) > -1) { outputStream.write(FILE_DATA ^ CRYPTO_SECRET_KEY); } inputStream.close(); outputStream.flush(); outputStream.close(); } /** * MultipartFile 生成臨時檔案 * @param multipartFile * @param tempFilePath 臨時檔案路徑 * @return File 臨時檔案 */ public static File multipartFileToFile(MultipartFile multipartFile,String tempFilePath) { File file = new File(tempFilePath); // 獲取檔案原名 String originalFilename = multipartFile.getOriginalFilename(); // 獲取檔案字尾 String suffix = originalFilename.substring(originalFilename.lastIndexOf(".")); if (!file.exists()) { file.mkdirs(); } // 建立臨時檔案 File tempFile = new File(tempFilePath + "\\" + UUID.randomUUID().toString().replaceAll("-","") + suffix); try { if (!tempFile.exists()) { // 寫入臨時檔案 multipartFile.transferTo(tempFile); } } catch (IOException e) { e.printStackTrace(); } return tempFile; } /** * 上傳檔案 * @param fileServerPath 檔案伺服器地址 * @param folderPath 存放的資料夾路徑(比如存放在檔案伺服器的 upload 資料夾下,即 ”/upload“) * @param uploadFile 需要上傳的檔案 * @param isCrypto 是否加密 * @return String 檔案上傳後的全路徑 */ public static String uploadByJersey(String fileServerPath,String folderPath,File uploadFile,boolean isCrypto) { String suffix = uploadFile.getName().substring(uploadFile.getName().lastIndexOf(".")); String randomFileName = UUID.randomUUID().toString().replaceAll("-","") + suffix; String fullPath = fileServerPath + folderPath + "/" + randomFileName; try { if (isCrypto) { // 建立加密檔案 File cryptoFile = new File(uploadFile.getPath().substring(0,uploadFile.getPath().lastIndexOf(".")) + "crypto" + uploadFile.getPath().substring(uploadFile.getPath().lastIndexOf("."))); // 執行加密 cryptoFile(uploadFile,cryptoFile); // 儲存加密後的檔案 uploadFile = cryptoFile; } // 建立 Jersey 伺服器 Client client = Client.create(); WebResource wr = client.resource(fullPath); // 上傳檔案 wr.put(String.class,fileToByte(uploadFile)); } catch (Exception e) { e.printStackTrace(); } return fullPath; } /** * 下載檔案 * @param url 檔案路徑 * @param filePath 檔案儲存路徑 * @param fileName 檔名稱(包含檔案字尾) * @param isCrypto 是否解密 * @return File */ public static File downloadByURL(String url,String filePath,String fileName,boolean isCrypto) { File file = new File(filePath); if (!file.exists()) { file.mkdirs(); } FileOutputStream fileOut; HttpURLConnection httpURLConnection; InputStream inputStream; try { URL httpUrl = new URL(url); httpURLConnection = (HttpURLConnection) httpUrl.openConnection(); httpURLConnection.setDoInput(true); httpURLConnection.setDoOutput(true); httpURLConnection.setUseCaches(false); httpURLConnection.connect(); inputStream = httpURLConnection.getInputStream(); BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream); if (!filePath.endsWith("\\")) { filePath += "\\"; } file = new File(filePath + fileName); fileOut = new FileOutputStream(file); BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOut); byte[] bytes = new byte[4096]; int length = bufferedInputStream.read(bytes); //儲存檔案 while (length != -1) { bufferedOutputStream.write(bytes,length); length = bufferedInputStream.read(bytes); } bufferedOutputStream.close(); bufferedInputStream.close(); httpURLConnection.disconnect(); } catch (Exception e) { e.printStackTrace(); } if (isCrypto) { try { // 建立解密檔案 File cryptoFile = new File(((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getServletContext().getRealPath("/") + "\\temp\\" + UUID.randomUUID().toString().replaceAll("-","") + file.getName().substring(file.getName().lastIndexOf("."))); // 執行解密 cryptoFile(file,cryptoFile); // 刪除下載的原檔案 file.delete(); // 儲存解密後的檔案 file = cryptoFile; } catch (Exception e) { e.printStackTrace(); } } return file; } /** * 刪除檔案伺服器上的檔案 * @param url 檔案路徑 * @return boolean */ public static boolean deleteByJersey(String url) { try { Client client = new Client(); WebResource webResource = client.resource(url); webResource.delete(); return true; } catch (UniformInterfaceException e) { e.printStackTrace(); } catch (ClientHandlerException e) { e.printStackTrace(); } return false; } /** * File轉Bytes * @param file * @return byte[] */ public static byte[] fileToByte(File file) { byte[] buffer = null; try { FileInputStream fileInputStream = new FileInputStream(file); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); byte[] bytes = new byte[1024]; int n; while ((n = fileInputStream.read(bytes)) != -1) { byteArrayOutputStream.write(bytes,n); } fileInputStream.close(); byteArrayOutputStream.close(); buffer = byteArrayOutputStream.toByteArray(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return buffer; } }
測試上傳
/** * @param multipartFile 上傳檔案 * @param isCrypto 是否加密檔案 * @return */ @Test public String upload(MultipartFile multipartFile,boolean isCrypto) { HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); // 生成臨時檔案 File tempFile = FileUtil.multipartFileToFile(multipartFile,request.getServletContext().getRealPath("/") + "\\static\\temp"); // 上傳檔案並返回檔案路徑 String uploadFilePath = FileUtil.uploadByJersey("http://localhost:8080","/upload",tempFile,isCrypto); if (uploadFilePath != null) { return "上傳成功"; } else { return "上傳失敗"; } }
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。