加密类:
public class FileEFS {
/**
* 文件上传,加密输出到制定路径
* @param file 上传文件
* @param encFilePath 输出路径
* @throws Exception
*/
public static void EncFile(MultipartFile file,String encFilePath) throws Exception {
CommonsMultipartFile cFile = (CommonsMultipartFile) file;
DiskFileItem fileItem = (DiskFileItem) cFile.getFileItem();
InputStream fis = fileItem.getInputStream();
File encFile = new File(encFilePath); //加密文件
if(fis==null){
System.out.println("上传文件为空");
return;
}
if(!encFile.exists()){
System.out.println("encrypt file created");
encFile.createNewFile();
}
OutputStream fos = new FileOutputStream(encFile);
int index;
byte[] bytes = new byte[1024];
byte[] bytes2 = new byte[1024];
while ((index = fis.read(bytes)) != -1) {
for (int j = 0; j<index;j++) {
bytes2[j] = (byte) (bytes[j]^numOfEncAndDec);
}
fos.write(bytes2, 0, index);
}
fis.close();
fos.flush();
fos.close();
}
}
Controller上传时调用加密方法:
FileEFS.EncFile(file, filePath);//MultipartFile上传文件,路径
Controller解密方法:
@RequestMapping(value = "getFileDecode", method=RequestMethod.GET)
public void getFileDecode(HttpServletRequest request,HttpServletResponse response ){
String fileName = request.getParameter("file");
InputStream fis = null;
ServletOutputStream out = null;
try {
String filePathString = request.getSession().getServletContext().getRealPath("/")+fileName;
File encFile = new File(filePathString);
fis = new FileInputStream(encFile);
out = response.getOutputStream();
int key = FileEFS.getSecretKey();
int index;
byte[] bytes = new byte[1024];
byte[] bytes2 = new byte[1024];
while ((index = fis.read(bytes)) != -1) {
for (int j = 0; j<index;j++) {
bytes2[j] = (byte) (bytes[j]^key);
}
out.write(bytes2, 0, index);
}
fis.close();
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
} finally{
try {
fis.close();
out.flush();
out.close();
} catch (IOException e2) {
e2.printStackTrace();
}
}
}
JSP获取以图片为例:
<img src="<%=basePath%>/getFileDecode?file=upload/${picture.Name}" style="width: 650px;height: 470px">