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