자바 파일 업로드 및 다운로드(암호 화 및 복호화 첨부)
8500 단어 Java
사용
Jersey
서버 업로드,사용HTTP
다운로드 요청도입 의존
관련 의존
com.sun.jersey
jersey-client
1.18.1
도구 클래스 만 들 기
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, 0, 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, 0, 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 " ";
}
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
JPA + QueryDSL 계층형 댓글, 대댓글 구현(2)이번엔 전편에 이어서 계층형 댓글, 대댓글을 다시 리팩토링해볼 예정이다. 이전 게시글에서는 계층형 댓글, 대댓글을 구현은 되었지만 N+1 문제가 있었다. 이번에는 그 N+1 문제를 해결해 볼 것이다. 위의 로직은 이...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.