Java blob file upload download

Source: Internet
Author: User

1. File Upload

Byte[] Type in Pojo, which corresponds to the BLOB type in the database.

Main code:

FileInputStream FIS = null;

FIS = new FileInputStream (new File (FilePath));
byte[] Inputbyte = Input2byte (FIS);
Filebean.setcontent (Inputbyte);

/**
* Convert Stream to 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, 1024x768)) > 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. File download

@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 ();//Gets the file name stored in the log
String useragent = Request.getheader ("User-agent"). toLowerCase ();
if (Useragent.contains ("MSIE") | | | useragent.contains ("like Gecko")) {
Ie
filename = urlencoder.encode (filename, "UTF-8");
} else {
Non-IE
filename = new String (filename.getbytes ("UTF-8"), "iso-8859-1");
}
try {

byte[] FileStream = Bean.getcontent ();

Download the file as a stream
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 file upload download

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.