java blob 檔案上傳下載

來源:互聯網
上載者:User

標籤:rac   red   over   agent   while   ogg   put   like   turn   

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 檔案上傳下載

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.