81,092
社区成员
发帖
与我相关
我的任务
分享
public Long uploadAlbumPhoto(File file, String accountId, String fileName,
AblumPhotoDto albumPhotoDto) {
String uploadPath = accountId + File.separator + albumPhotoDto.getAlbumId();
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
InputStream imageIs = null;
Long albumPhotoId = null;
try {
File path = new File(albumPath + File.separator + uploadPath); // 存放照片的文件夹根据用户的id与相册id分文件夹存放
if (!path.exists()) {
path.mkdirs();
}
// 生成新的文件名
Long start = System.currentTimeMillis();
String middle = StringTools.getRandomStr(10);
String suffixFileName = fileName.substring(fileName.lastIndexOf("."));
String newFileName = start.toString() + "_" + middle + suffixFileName;
File destFile = new File(path, newFileName); // 得到图片保存的位置(根据root来得到图片保存的路径在tomcat下的该工程里)
bis = new BufferedInputStream(new FileInputStream(file), 102400);
bos = new BufferedOutputStream(new FileOutputStream(destFile), 102400);
byte[] buffer = new byte[102400];
int length = 0;
while ((length = bis.read(buffer)) != -1) {
bos.write(buffer, 0, length);
}
bos.flush();
int size = (int) (destFile.length() / 1024);
imageIs = new FileInputStream(destFile);
BufferedImage buff = ImageIO.read(imageIs);
int high = buff.getHeight();
int width = buff.getWidth();
// 生成缩略图,大小为宽232像素,高为178像素
ImageSlimUtil.saveMinImageByParam(albumPath, (File.separator + uploadPath).replace("\\", "/"), (File.separator + newFileName).replace("\\", "/"), 232, 178);
albumPhotoId = sequenceDao.getSequence(SequenceEnum.Album_Photo_Sequence.name);
String photoName = fileName.substring(0, fileName.lastIndexOf("."));
TAblumPhoto tAlbumPhoto = this.albumPhotoDtoToPo(albumPhotoDto);
tAlbumPhoto.setSequenceId(albumPhotoId);
tAlbumPhoto.setPhotoUrl(uploadPath + File.separator + newFileName);
tAlbumPhoto.setPhotoName(photoName);
tAlbumPhoto.setSize(Integer.valueOf(size));
tAlbumPhoto.setHigh(String.valueOf(high));
tAlbumPhoto.setWidth(String.valueOf(width));
tAlbumPhoto.setCreateDate(new Date());
if (tAlbumPhoto.getPohotoStatus() == null) {
tAlbumPhoto.setPohotoStatus("1");
}
// 在第一次给用户的某个相册上传照片时,设置上传的第一张默认为这个相册的封面
List<TAblumPhoto> photoList = albumPhotoDao.findAlbumPhoto(albumPhotoDto.getAlbumId());
if (photoList != null && photoList.size() > 0) {
tAlbumPhoto.setCover("0");
} else {
tAlbumPhoto.setCover("1");
}
albumPhotoDao.saveAlbumPhoto(tAlbumPhoto);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (bis != null) {
bis.close();
bis = null;
}
if (bos != null) {
bos.close();
bos = null;
}
if (imageIs != null) {
imageIs.close();
imageIs = null;
}
} catch (IOException e) {
e.printStackTrace();
}
}
return albumPhotoId;
}