java blob 文件上传下载

Posted 月眸 eyesmoon

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java blob 文件上传下载相关的知识,希望对你有一定的参考价值。

1、文件上传

pojo中为byte[] 类型,数据库中对应为blob类型。

主要代码:

FileInputStream fis = null;

fis = new FileInputStream(new File(filePath));
byte[] inputByte = input2byte(fis);
fileBean.setContent(inputByte);

 

/**
* 将 流 转换为byte
* @param inStream
* @return
* @throws IOException
*/
public static final byte[] input2byte(InputStream inStream) throws IOException {
ByteArrayOutputStream swapStream = null;
try {
swapStream = new ByteArrayOutputStream();
byte[] buff = new byte[1024];
int rc = 0;
while ((rc = inStream.read(buff, 0, 1024)) > 0) {
swapStream.write(buff, 0, rc);
}
return swapStream.toByteArray();
} catch (Exception e) {
logger.info(e.getStackTrace());
} finally {
if (swapStream != null) {
safeClose(swapStream);
}
}
return null;
}

 

2、文件下载

@Override
public void downFileByBlob(HttpServletRequest request, HttpServletResponse response, String fileId) throws IOException {
AtFileupload bean = hibernateDao.getObject(AtFileupload.class, fileId);
if (bean.getContent() != null) {
String filename= bean.getFileName();//获取日志中存储的文件名称
String userAgent = request.getHeader("user-agent").toLowerCase();
if (userAgent.contains("msie") || userAgent.contains("like gecko")) {
// IE
filename = URLEncoder.encode(filename, "UTF-8");
} else {
// 非IE
filename = new String(filename.getBytes("UTF-8"), "iso-8859-1");
}
try {

byte[] fileStream = bean.getContent();

// 以流的形式下载文件
response.setContentType("application/x-msdownload");
response.setCharacterEncoding("UTF-8");
response.setHeader("Content-Disposition", "attachment; filename=" + filename);
OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
toClient.write(fileStream);
toClient.flush();
toClient.close();

} catch (Exception e) {
logger.info(e.getStackTrace());
}
}
}

 

























































以上是关于java blob 文件上传下载的主要内容,如果未能解决你的问题,请参考以下文章

急急急:上传照片到BLOB字段问题~

使用java中的azure函数将文件从浏览器上传到azure blob存储

如何将 AppendBlob/大于 4mb 限制的文件上传到 Java 中的 Azure 存储/Blob?

Azure Blob 存储 - 在将新文件上传到 Blob 容器中的特定文件夹时设置警报

用java实现文件的上传与下载

如何在 DotNetCore 的 Blob 存储中上传多个文件