Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public static String getContentDisposition(Response response, String filename) throws Exception {
- String disposition = "attachment; ";
- if (asciiEncoder.canEncode(filename))
- disposition += "filename=\"" + filename + "\"";
- else {
- String encodedFilename = urlEncoder.encode(filename, response.encoding);
- disposition += "filename*=" + response.encoding + "''" + encodedFilename + "; filename=\"" + encodedFilename + "\"";
- }
- return disposition;
- }
- public static void streamFileToResponse(Response response, File file, String filename, String mimeType, int bufferSize, int maxBytesPerSecond) throws Exception {
- FileInputStream fis = null;
- BufferedInputStream bs = null;
- try {
- fis = new FileInputStream(file);
- bs = new BufferedInputStream(fis, bufferSize);
- prepareResponseStreamForFile(response, filename, file.length(), mimeType);
- channelStreamToResponse(response, bs, bufferSize, maxBytesPerSecond);
- } finally {
- if (bs != null)
- bs.close();
- if (fis != null)
- fis.close();
- }
- }
- public static void prepareResponseStreamForFile(Response response, String filename, long length, String mimeType) throws Exception {
- response.out.reset();
- response.contentType = mimeType;
- response.setHeader("Content-Disposition", getContentDisposition(response, filename));
- response.setHeader("Content-Length", String.valueOf(length));
- }
- public static void channelStreamToResponse(Response response, InputStream inputStream, int bufferSize, int maxBytesPerSecond) throws Exception {
- InputStream is = null;
- try {
- is = new ThrottledInputStream(inputStream, maxBytesPerSecond);
- byte[] buf = new byte[bufferSize];
- int readBytesLen = 0;
- response.out.reset();
- int flushCnt = 0;
- while ((readBytesLen = is.read(buf)) > 0) {
- if (readBytesLen != bufferSize)
- response.writeChunk(Arrays.copyOf(buf, readBytesLen));
- else
- response.writeChunk(buf);
- if (flushCnt++ > 7 || readBytesLen <= 0) {
- response.out.flush();
- flushCnt = 0;
- }
- }
- response.out.flush();
- } catch (Exception ex) {
- response.out = null;
- System.gc();
- throw ex;
- } finally {
- if (is != null)
- is.close();
- if (inputStream != null)
- inputStream.close();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment