import org.springframework.web.multipart.MultipartFile; import org.apache.http.entity.ContentType; import sun.misc.BASE64Decoder;
/** * 将base64字符解码保存文件 * * @param base64Code * @throws Exception */ private String decoderBase64File(String base64Code) throws Exception { String targetPath=getTargetPath(); String catalogue=System.currentTimeMillis()+".mp3"; File file = new File(targetPath); if(file.exists()==false){ file.mkdirs(); } byte[] buffer = new BASE64Decoder().decodeBuffer(base64Code); FileOutputStream out = new FileOutputStream(targetPath+"/"+catalogue); out.write(buffer); out.close(); //调用文件上传接口上传生成文件 String oid= this.uploadFileByPath(targetPath+"/"+catalogue); return oid; } /** * 获取一个临时地址使用 * @return */ private String getTargetPath(){ if(CommonUtil.isWindows()){ //给一个固定的地址临时使用 return "D://"+ "templates/notice/"+ DateUtil.getYear()+"/"+ DateUtil.getMonth()+"/"+DateUtil.getDay(); }else{ //替换成功报存的文件路径 return "/soft/usr/local/zfsoft/zc/notice/"+ DateUtil.getYear()+"/"+ DateUtil.getMonth()+"/"+DateUtil.getDay(); } } /** * 根据路径将文件上传到服务器 * @param path * @return */ private String uploadFileByPath(String path){ try { HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); File pdfFile = new File(path); FileInputStream fileInputStream = new FileInputStream(pdfFile); MultipartFile multipartFile = new MockMultipartFile(pdfFile.getName(), pdfFile.getName(), ContentType.APPLICATION_OCTET_STREAM.toString(), fileInputStream); SysAtta atta= this.uploadFile(request,multipartFile); if(atta!=null){ return atta.getAttaOid(); } }catch (Exception e){ e.printStackTrace(); } return null; } public SysAtta uploadFile(HttpServletRequest request, MultipartFile file) throws Exception { //登录信息 CurrentLoginUser loginUser = CurrentLoginUserHolder.getCurrentLoginUser(); //判断file数组不能为空并且长度大于0 UploadUtil uploadUtil = new UploadUtil(request); String filePath = null; if (!file.isEmpty()) { try { // 上传并返回新文件名称 if(file.getOriginalFilename()!=null){ file = new MockMultipartFile("File",file.getOriginalFilename(),"text/plain", file.getInputStream()); } filePath = uploadUtil.uploadFile(file); SysAttaTemp sysAttaFile = uploadUtil.getSysAttaFile(filePath, loginUser.getUserOid()); SysAtta sysAtta = new SysAtta(); org.springframework.beans.BeanUtils.copyProperties(sysAttaFile,sysAtta); //保存附件信息 ApiResultSet<SysAtta> atta = sysAttaFeginService.saveSysAtta(sysAtta); return atta.getData(); } catch (IOException e) { e.printStackTrace(); } } return null; }
/**
* 将文件转成base64 字符串
*
* @param path文件路径
* @return *
* @throws Exception
*/
public
static
String encodeBase64File(String path)
throws
Exception {
File file =
new
File(path);
FileInputStream inputFile =
new
FileInputStream(file);
byte
[] buffer =
new
byte
[(
int
) file.length()];
inputFile.read(buffer);
inputFile.close();
return
new
BASE64Encoder().encode(buffer);
}