前段页面
控制层:
1.接收文件file
2.存储Byte[]
public AttachmentInfo uploadAttachment(MultipartFile file) {
// 文件后缀
String extension = getFileExtension(file.getOriginalFilename());
// 文件名
String attachmentName = getFileName(file.getOriginalFilename());
// 文件大小
double attachmentSize = (double) ((file.getSize() * 1.0) / (1024 * 1024));
attachmentSize = (double) (Math.round(attachmentSize * 100)) / 100;
AttachmentInfo info = new AttachmentInfo();
info.setAttachmentName(attachmentName);
info.setAttachmentType(extension);
info.setAttachmentSize(Double.toString(attachmentSize));
try {
attachmentMapper.addAttachment(info, file.getBytes());
} catch (IOException e) {
throw new FrameworkException("文件保存异常");
}
return info;
}
dao层:
void addAttachment(@Param(“attachmentInfo”) AttachmentInfo attachmentInfo, @Param(“file”) byte[] file);
mapper层:
SELECT
(LPAD(CAST(SEQ_SYS_ATTACHMENT_INFO.NEXTVAL AS VARCHAR2(20)),20,‘0’))
FROM DUAL
insert into sys_attachment_info (attachment_id, attachment_name, attachment_type, attachment_size, attachment)
values (#{attachmentInfo.attachmentId},
#{attachmentInfo.attachmentName},
#{attachmentInfo.attachmentType},
#{attachmentInfo.attachmentSize},
#{file, javaType=byte[], jdbcType=BLOB, typeHandler=org.apache.ibatis.type.BlobTypeHandler})
</insert>
注:byte[]转BLOB时 需要配 typeHandler=org.apache.ibatis.type.BlobTypeHandler
<result column="BLOBName"property=“byteArray” jdbcType=“BLOB” typeHandler=“org.apache.ibatis.type.BlobTypeHandler”/>
上传文件 磁盘存储
@Override
public AttachmentInfo uploadAttachment(MultipartFile file) {
String preUrl = PropertyUtils.getString("preUrl");
String baseDir = PropertyUtils.getString("baseDir");
SimpleDateFormat dFormat = new SimpleDateFormat("yyyyMMdd");
String date = dFormat.format(new Date());
// 文件后缀
String extension = getFileExtension(file.getOriginalFilename());
// 文件名
String attachmentName = getFileName(file.getOriginalFilename());
// 新的文件名
String newFileName = UUID.randomUUID().toString() + extension;
// 文件大小
double attachmentSize = (double) ((file.getSize() * 1.0) / (1024 * 1024));
attachmentSize = (double) (Math.round(attachmentSize * 100)) / 100;
// 文件服务器路径
String fileDir = baseDir + "/" + date;
String filePath = fileDir + "/" + newFileName;
// DB保存路径
String attachmentUrl = preUrl + "/" + date + "/" + newFileName;
File fileFile = new File(fileDir);
if (!fileFile.exists()) {
fileFile.mkdirs();
}
// 写入磁盘
try {
InputStream in = file.getInputStream();
FileOutputStream fos = new FileOutputStream(filePath);
byte[] buffer = new byte[1024];
int len = 0;
while ((len = in.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
fos.close();
in.close();
} catch (Exception e) {
throw new FrameworkException("文件写入异常");
}
AttachmentInfo attachmentInfo = new AttachmentInfo();
attachmentInfo.setAttachmentName(attachmentName);
attachmentInfo.setAttachmentSize(attachmentSize + "");
attachmentInfo.setAttachmentSrc(attachmentUrl);
attachmentInfo.setAttachmentType(extension);
return attachmentInfo;
}