I am using the following code to download a file within the WEB-INF
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String b = null;
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookie.getName().equals("thecookie")) {
b = cookie.getValue();
}
}
}
BufferedReader br = new BufferedReader(new FileReader(b+"/logs.txt"));
String path = br.readLine();
br.close();
File file = new File(path+"/Results.xlsx");
FileInputStream fileIn = new FileInputStream(file);
ServletOutputStream out = response.getOutputStream();
response.setHeader("Content-Disposition", "attachment; filename=Result.xlsx");
response.setContentType(
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
byte[] outputByte = new byte[4096];
int bytesRead;
//copy binary contect to output stream
while((bytesRead = fileIn.read(outputByte)) != -1)
{
out.write(outputByte, 0, bytesRead);
}
fileIn.close();
out.flush();
out.close();
}
along with this I want to download another file at the same location Results.csv I've tried using the same code above twice but it didn't work.
How to download multiple files without using zipoutputstream?
MIME/multipart responses are, as far as I know, not part of the HTTP standard. Some browsers seem to support it, but I recommend against using it.
Instead, you could pack those files into a ZIP file (using a ZipOutputStream), and return that as your response. That's also the way DropBox handles the download of multiple files at once.
It is possible but having them in separate requests if you plan to work within every browser.
Here a sample script for downloading a file via javascript
function downloadFile(url, name) {
var link = document.createElement("a");
link.download = name;
link.href = url;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
delete link;
}
downloadFile(url1,filenam1);
downloadFile(url2,filenam2);
downloadFile(url3,filenam3);
...
Related
I faced with the issue that after uploading zip file on a server it cannot be unzipped.
I have REST API based on Dropwizard framework with next endpoint example:
#Consumes(MediaType.MULTIPART_FORM_DATA)
#Produces(MediaType.APPLICATION_JSON)
#Path("/zip")
public class ImportResource {
#POST
public Response fileService(#FormDataParam("fileData") InputStream fileDataInputStream,
#FormDataParam("fileData") FormDataContentDisposition fileDataDetail) {
File newFile = new File("/Users/alexx/Documents/"+ fileDataDetail.getFileName());
try {
final OutputStream out = new FileOutputStream(newFile);
ByteStreams.copy(fileDataInputStream, out);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return Response.ok().build();
}
// save uploaded file to new location
private void writeToFile(InputStream uploadedInputStream, String uploadedFileLocation) throws IOException {
int read;
final int BUFFER_LENGTH = 1024;
final byte[] buffer = new byte[BUFFER_LENGTH];
OutputStream out = new FileOutputStream(new File(uploadedFileLocation));
while ((read = uploadedInputStream.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
out.flush();
out.close();
}
Also in Application class I provided appropriate classes:
....
bootstrap.addBundle(new MultiPartBundle());
....
environment.jersey().register(MultiPartFeature.class);
After uploading zip file, it looks like it uploads, but it cannot be unzipped, next message received:
(Error 1 - Operation not permitted).
Text and image files uploads and opens correctly.
Did I skip anything? Should I add additional params or setting somewhere?
Thank you for answers!
It was my mistake.
I found the filter which works with payload before it comes to a resource.
The filter has next code:
payload = IOUtils.toString(requestContext.getEntityStream(), StandardCharsets.UTF_8);
if (payload != null) {
RequestPayloadHolder.getRequestPayload().setPayload(payload);
InputStream in = IOUtils.toInputStream(payload, StandardCharsets.UTF_8);
requestContext.setEntityStream(in);
}
So entity with multipart/form-data cannot be transferred to String and otherwise correctly.
Before this request implementation all other request payloads were JSON.
I have to be more careful.
I use this Java code to download files from a web application:
#RequestMapping(value = "/filedownloads/filedownload/{userid}/{projectid}/{documentfileid}/{version}/", method = RequestMethod.GET)
public void filesDownload(final #PathVariable("userid") String userId, final #PathVariable("projectid") String projectId,
final #PathVariable("documentfileid") String documentFileId, final #PathVariable("version") String version,
final HttpServletResponse response) throws IOException, BusinessException {
...
final String fileName = "filename=" + documentFile.getFileName();
final InputStream is = new FileInputStream(filePath);
response.setHeader("Content-Disposition", "inline; " + fileName);
IOUtils.copy(is, response.getOutputStream());
response.flushBuffer();
}
if I will download a pptx- file I get the following IE- page:
What I want to do is to open the downloaded file in Powerpoint.
My question now would be if there is a header setting in order to open this file with the right application (in this case Powerpoint)
Simply try to set the Content Type header properly which is application/vnd.openxmlformats-officedocument.presentationml.presentation in case a pptx, as next:
response.setContentType(
"application/vnd.openxmlformats-officedocument.presentationml.presentation"
);
response.setHeader(
"Content-Disposition",
String.format("inline; filename=\"%s\"", documentFile.getFileName())
);
response.setContentLength((int) new File(filePath).length());
Here is the list of mime types corresponding to Office 2007 documents.
Here is a little sample code from a Spring MVC Controller:
#RequestMapping("/ppt")
public void downloadPpt(HttpServletRequest request, HttpServletResponse response) throws IOException {
Resource resource = new ClassPathResource("Presentation1.pptx");
InputStream resourceInputStream = resource.getInputStream();
response.setHeader("Content-Disposition", "attachment; filename=\"Presentation1.pptx\"");
response.setContentLengthLong(resource.contentLength());
byte[] buffer = new byte[1024];
int len;
while ((len = resourceInputStream.read(buffer)) != -1) {
response.getOutputStream().write(buffer, 0, len);
}
}
By setting the Content-Disposition to attachment, you're telling the browser to download this file as an attachment and by supplying the correct file name with extension, you're telling the Operating System to use whatever application the user normally uses to open a file of this type. In this case it will be MS Power Point.
This way you can get away with not knowing exactly what version of Power Point the file was created with.
I have tested code in IE-11 its work fine. See below code i.e
#RequestMapping(value = "/downloadfile", method = RequestMethod.GET)
#ResponseBody
public void downloadfile(HttpServletRequest request, HttpServletResponse response) throws Exception {
ServletOutputStream servletOutputStream = null;
try {
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment; filename=downloadppt.pptx");
byte[] ppt = downloadFile();
servletOutputStream = response.getOutputStream();
servletOutputStream.write(ppt);
} catch (Exception e) {
throw e;
} finally {
servletOutputStream.flush();
servletOutputStream.close();
}
}
Generate bytes from saved pptx file.
public byte[] downloadFile() throws IOException {
InputStream inputStream = new FileInputStream(new File("e:/testppt.pptx"));
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
// Transfer bytes from source to destination
byte[] buf = new byte[1024];
int len;
while ((len = inputStream.read(buf)) > 0) {
byteArrayOutputStream.write(buf, 0, len);
}
inputStream.close();
byteArrayOutputStream.close();
return byteArrayOutputStream.toByteArray();
}
That's it, you are able to download pptx file. Hope code help you, if you have any query or doubt then we can discuss or if any suggestions. Thank you
I'm trying to download an.APK on Android's Chrome from my Glassfish server, but all I got is a "zero kb" file.
On Windows(PC)'s Chrome and on Android's Firefox it works correctly.
I'm using the following code:
private void downloadAPK(HttpServletRequest request, HttpServletResponse response, PrintWriter out){
String file = "/usr/local/glassfish4/glassfish/domains/domain1/applications/foo/foo.apk";
FileInputStream inputStream = null;
try{
File downloadFile = new File(file);
inputStream = new FileInputStream(downloadFile);
response.setHeader("Content-Disposition","attachment;filename="+file.getName());
int c = 0;
while ((c = inputStream.read()) != -1)
out.write(c);
} catch (Exception e) {
// code
}
// closing code
}
There is something that I'm missing to make it work on Android's Chrome?
I have file on the server & that I want to download on my machine using browser. But I am not getting an option from browser to download the file.
My code is
JSP
<div id="jqgrid">
<table id="grid"></table>
<div id="pager"></div>
</div>
JS
jq("#grid").jqGrid({
....
onCellSelect: function(rowid, index, contents, event) {
...
var fileName = jQuery("#grid").jqGrid('getCell',rowid,'fileName');
$scope.downloadFile(fileName);
}
});
$scope.downloadFile = function(fileName) {
$http({
url: "logreport/downLoadFile",
method: "GET",
params: {"fileName": fileName}
});
};
Controller
#RequestMapping(value = "/downLoadFile", method = RequestMethod.GET)
public void downLoadFile(HttpServletRequest request, HttpServletResponse response) {
try {
String fileName = request.getParameter("fileName");
File file = new File(filePath +"//"+fileName);
InputStream in = new BufferedInputStream(new FileInputStream(file));
response.setContentType("application/xlsx");
response.setHeader("Content-Disposition", "attachment; filename="+fileName+".xlsx");
ServletOutputStream out = response.getOutputStream();
IOUtils.copy(in, out);
response.flushBuffer();
} catch (Exception e) {
e.printStackTrace();
}
}
I am not getting any exception but not sure why browser dialog is not opening to download the file. Also where is it exactly downloading the file?
#SotiriosDelimanolis was right. File download is not possible using ajax request.
Simply use 'window.location'.
$scope.downloadFile = function(fileName) {
window.location.href = 'logreport/downLoadFile?fileName=asdad1';
};
I didn't have enough credit to give a comment so wiritting here.. Thanks user1298426. I was strugling like anything for this. I was trying with AJAX. With window.location.href, I can download file in browser...
MY javascript code is as follows:
jQuery('#exportToZip').click(function() {
window.location.href = '*****';
});
*****: is the url mapping that I have in controller.
#RequestMapping(value = "/****")
#ResponseBody
public void downloadRequesthandler(HttpServletRequest request,HttpServletResponse response) {
String status;
try {
filedownloader.doGet(request, response);
} catch (ServletException e) {
status="servlet Exception occured";
e.printStackTrace();
} catch (IOException e) {
status="IO Exception occured";
e.printStackTrace();
}
//return status;
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ServletContext context = request.getServletContext();
// construct the complete absolute path of the file
File downloadFile = new File(filePath);
System.out.println("downloadFile path: "+ filePath);
FileInputStream inputStream = new FileInputStream(downloadFile);
// get MIME type of the file
String mimeType = context.getMimeType(fullPath);
if (mimeType == null) {
// set to binary type if MIME mapping not found
mimeType = "application/octet-stream";
}
System.out.println("MIME type: " + mimeType);
response.setContentLength((int) downloadFile.length());
// set headers for the response
String headerKey = "Content-Disposition";
String headerValue = String.format("attachment; filename=\"%s\"",downloadFile.getName());
response.setHeader(headerKey, headerValue);
OutputStream outStream = response.getOutputStream();
byte[] buffer = new byte[BUFFER_SIZE];
System.out.println("buffer: "+ buffer.length);
int bytesRead = -1;
// write bytes read from the input stream into the output stream
//be carefull in this step. "writebeyondcontentlength" and "response already committed" error is very common here
while ((bytesRead = inputStream.read(buffer))!=-1 ) {
outStream.write(buffer, 0, bytesRead);
}
inputStream.close();
outStream.close();
}
Trying to download file with ajax is a blunder....
cheers......
Instead of using IOUtils copy method
ServletOutputStream out = response.getOutputStream();
IOUtils.copy(in, out);
You can use following :
ServletOutputStream out = response.getOutputStream();
byte[] bytes = IOUtils.toByteArray(in);
out.write(bytes);
out.close();
out.flush();
Hope this will work.
I'm trying here to add a specific dialog bean for action on Alfresco Explorer that supposed to download a specific docx file. The code is working fine when I hit the download action, it downloads the file but as mentioned in my question title, the file size is 0 bytes.
I'm using this to do that:
public class NewFormDialog extends BaseDialogBean {
protected String aspect;
protected String finishImpl(FacesContext context, String outcome)
throws Exception {
download(aspect);
// // get the space the action will apply to
// NodeRef nodeRef = this.browseBean.getActionSpace().getNodeRef();
//
// // resolve the fully qualified aspect name
// QName aspectToAdd = Repository.resolveToQName(this.aspect);
//
// // add the aspect to the space
// getNodeService().addAspect(nodeRef, aspectToAdd, null);
//
// // return the default outcome
return outcome;
}
public boolean getFinishButtonDisabled() {
return false;
}
public String getFinishButtonLabel() {
return "Download";
}
public void download(String pAspect) throws ServletException, IOException {
String filename = pAspect;
String filepath = "\\";
BufferedInputStream buf = null;
ServletOutputStream myOut = null;
try {
FacesContext fc = FacesContext.getCurrentInstance();
HttpServletResponse response = (HttpServletResponse) fc
.getExternalContext().getResponse();
myOut = response.getOutputStream();
File myfile = new File(filepath + filename);
// set response headers
response.setContentType("application/octet-stream");
response.addHeader("Content-Disposition", "attachment; filename="
+ filename);
response.setContentLength((int) myfile.length());
FileInputStream input = new FileInputStream(myfile);
buf = new BufferedInputStream(input);
int readBytes = 0;
// read from the file; write to the ServletOutputStream
while ((readBytes = buf.read()) != -1)
myOut.write(readBytes);
myOut.flush();
response.flushBuffer();
} catch (IOException ioe) {
throw new ServletException(ioe.getMessage());
} finally {
// close the input/output streams
if (myOut != null)
myOut.close();
if (buf != null)
buf.close();
FacesContext.getCurrentInstance().responseComplete();
}
}
public String getAspect() {
return aspect;
}
public void setAspect(String aspect) {
this.aspect = aspect;
}
}
I tried every solution that I found by none works.
Thank you in advance.
The File.length() method returns 0 if the file does not exist. Check to make sure that the file exists.
Tip: The Apache Commons IO library simplifies many I/O related tasks. For example, the following code snippet streams the contents of a file to the servlet response:
HttpServletResponse response = ...
File myfile = ...
InputStream in = null;
OutputStream out = null;
try {
in = new FileInputStream(myfile);
out = response.getOutputStream();
IOUtils.copy(in, out);
} finally {
IOUtils.closeQuietly(in); //checks for null
IOUtils.closeQuietly(out); //checks for null
}