I have JBoss running as application server and somewhere on my HD there is a PDF file, that gets created when the user clicks on a specific action. Let's say the file is here: C:/PDF/doonot/10.07.2012/doonot.pdf. How can I offer this file as download? I already did it for a CSV file, but I don't know how to do it with PDF.
Any help is much appreciated.
as i wrote on Is there a common way to download all types of files in jsp?
you can use something like this:
public HttpServletResponse getFile (HttpServletRequest request ,HttpServletResponse httpServletResponse, .......){
HttpServletResponse response = httpServletResponse;
InputStream in =/*HERE YOU READ YOUR FILE AS BinaryStream*/
String filename = "";
String agent = request.getHeader("USER-AGENT");
if (agent != null && agent.indexOf("MSIE") != -1)
{
filename = URLEncoder.encode(/*THIS IS THE FILENAME SHOWN TO THE USER*/, "UTF8");
response.setContentType("application/x-download");
response.setHeader("Content-Disposition","attachment;filename=" + filename);
}
else if ( agent != null && agent.indexOf("Mozilla") != -1)
{
response.setCharacterEncoding("UTF-8");
filename = MimeUtility.encodeText(/*THIS IS THE FILENAME SHOWN TO THE USER*/, "UTF8", "B");
response.setContentType("application/force-download");
response.addHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
}
BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
byte by[] = new byte[32768];
int index = in.read(by, 0, 32768);
while (index != -1) {
out.write(by, 0, index);
index = in.read(by, 0, 32768);
}
out.flush();
return response;
}
UPDATE:
Dont forget that you can use the InputStream as this:
// read local file into InputStream
InputStream inputStream = new FileInputStream("c:\\SOMEFILE.xml");
or you can use it even like this
//read from database
Blob blob = rs.getBlob(1);
InputStream in = blob.getBinaryStream();
You can simply write a servlet wich read the pdf and write it to the response output stream.
Exemple here : http://www.java-forums.org/blogs/servlet/668-how-write-servlet-sends-file-user-download.html
Yes Gustav is right. Java doesn't discriminate amongst file types. A file is a file, if you did it for csv, it should also work for pdf.
Related
I have one spring controller, I want to download file in specific path like D:// or K://, But right now it will be download in downloads folder by default.
I am taking my file from /WEB-INF/ folder (server side located in Tomcat folder) and i want to write in client machine D:\ drive please see my below code is something wrong please let me know. I am using google crome.
Thanks in Advance
public void downloadFile(HttpServletRequest request,
HttpServletResponse response) throws IOException {
//ServletContext context = request.getServletContext();
String filePath = request.getSession().getServletContext().getRealPath("/WEB-INF/") + "/"+"out.json";
// get absolute path of the application
ServletContext context = request.getServletContext();
String appPath = context.getRealPath("");
System.out.println("appPath = " + appPath);
// construct the complete absolute path of the file
//String fullPath = appPath + filePath;
File downloadFile = new File(filePath);
FileInputStream inputStream = new FileInputStream(downloadFile);
// get MIME type of the file
String mimeType = context.getMimeType(filePath);
if (mimeType == null) {
// set to binary type if MIME mapping not found
mimeType = "application/octet-stream";
}
System.out.println("MIME type: " + mimeType);
// set content attributes for the response
response.setContentType(mimeType);
response.setContentLength((int) downloadFile.length());
// set headers for the response
String headerKey = "Content-Disposition";
String headerValue = String.format("attachment; filename=\"%s\"",
downloadFile.getName());
System.out.println("downloadFile.getName()" + downloadFile.getName());
response.setHeader(headerKey, headerValue);
// get output stream of the response
OutputStream outStream = response.getOutputStream();
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead = -1;
// write bytes read from the input stream into the output stream
while ((bytesRead = inputStream.read(buffer)) != -1) {
outStream.write(buffer, 0, bytesRead);
}
inputStream.close();
outStream.close();
}
You cannot decide where the client will save the downloaded file on server side - in fact, you cannot even affect whether it will save it anywhere at all! That's for the client (e.g. Chrome) to decide.
See Chrome help for how to change default download location in Chrome.
Need a servlet to download a file from path like /home/Bureau.. in jee gwt
I used this but isn't work
and I went to download all file's type image
String filePath = request.getParameter("file");
String fileName = "test";
FileInputStream fileToDownload = new FileInputStream(filePath);
// ServletOutputStream output = response.getOutputStream();
response.setHeader("Content-Type", "image/png");
//response.setContentType("image/png");
response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + ".png\"");
// response.setContentLength(fileToDownload.available());
int readBytes = 0;
byte[] buffer = new byte[10000];
while ((readBytes = fileToDownload.read(buffer, 0, 10000)) != -1) {
//output.write(readBytes);
response.getOutputStream().write(readBytes);
}
response.getOutputStream().close();
fileToDownload.close();
fileToDownload.close();
The problem is at below line where you are writing no of bytes not actual bytes. Here readBytes represents no of bytes read at a time where as buffer contains actual bytes that is read.
response.getOutputStream().write(readBytes);
Try
OutputStream outputStream = response.getOutputStream();
while ((readBytes = fileToDownload.read(buffer)) != -1) {
outputStream.write(buffer,0,readBytes);
}
outputStream.close();
I suggest you to call response.getOutputStream() single time.
Your code will give you IndexOutOfBoundsException if the size of the file is less than 10000 bytes because of below line
fileToDownload.read(buffer, 0, 10000)
Change it to
fileToDownload.read(buffer)
Use ServletContext to get file path.
ServletContext context = getServletContext();
For more info have a look at below posts:
Writing image to servlet response with best performance.
How do I return an image from a servlet using ImageIO?
I'm making a fairly basic site for my mother, and seeing as I did some stuff in Java EE and with EJB during college last semester, I'm going to stick to this.
The only issue I am having is uploading images - I can't seem to find any examples.
I'm using entity classes and parameterised queries. This is the code for writing to the database, which is working fine, I'm just setting the blob image value to null for the moment.
#Override
public void addClothes(String designer, String cname, String ctype, String desc) {
Clothes c = new Clothes();
em.persist(c);
c.setDesigner(designer);
c.setCname(cname);
c.setCtype(ctype);
c.setDescript(desc);
c.setImage(null);
}
I have a servlet that takes a file, I'm just not sure how the file, when passed, should be sorted and what I should write to the database (from what I'm seeing, it's byte[])
A hand in the right direction would be appreciated!
Once you have the file on the server, either in memory or in a local or temp file (that depends on the framework or libraries that you're using), you will have a reference of a wrapper type.
If you are using Apache Commons File Upload, you have a FileItem reference. For request all contents of the file as byte array:
byte[] contents = fileItem.get();
If you are using Tomahawk of Trinidad, you have a org.apache.myfaces.trinidad.model.UploadedFile reference. For request all contents of the file as byte array, you can use class IOUtils of the Apache Commons IO:
byte[] contents = IOUtils.toByteArray(uploadedFile.getInputStream());
Of if you have a reference of org.apache.myfaces.custom.fileupload.UploadedFile, is more simple:
byte[] contents = uploadedFile.getBytes();
UPDATE
If you are using Java EE 6, you can use new features of Server 3.0 specification for upload files without extra libraries. See the excellent tutorial of BalusC in The BalusC Code: Uploading files in Servlet 3.0
To work with hibernatehttp://www.mkyong.com/hibernate/hibernate-save-image-into-database/
To work with JDBC:
To Write image into database BLOB using Jdbc , You need to Convert the File into Inputstream. statement.setBinaryStream(2, (InputStream) inputStream,(int) (image.length())); PreparedStatement statement offer method setBinaryStream() which is used to write binary stream into database BLOB column.
Here is a code snippet to help you:
File image = new File("C:/test.jpg");
inputStream = new FileInputStream(image);
Prepared statement = //define as per your table
// set the file binary stream
statement.setBinaryStream(2, (InputStream) inputStream,(int) (image.length()));
statement.executeUpdate();
In your Clothes class, you can add:
#Lob
private byte[] image;
// Getter/Setter methods
Got it working ! Somewhat, with this code:
public void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
out = response.getWriter();
final String path = "clothesImages" + File.separator + request.getParameter("designer") + File.separator + request.getParameter("ctype") + File.separator + request.getParameter("cname");
out.println(path);
String currentDir = new File(".").getAbsolutePath();
out.println(currentDir);
final Part filePart = request.getPart("image");
final String filename = "image.jpg";
File file = new File(path);
if (!file.exists()){
out.println("Dir Doesn't Exist");
file.mkdirs();
}
OutputStream outstream = null;
InputStream filestream = null;
try{
outstream = new FileOutputStream(new File(path + File.separator + filename));
filestream = filePart.getInputStream();
int read = 0;
final byte[] bytes = new byte[1024];
while(( read = filestream.read(bytes)) != -1){
outstream.write(bytes, 0, read);
}
out.println("New file " + filename + " created at " + path);
}catch (FileNotFoundException fne) {
out.println("You either did not specify a file to upload or are "
+ "trying to upload a file to a protected or nonexistent "
+ "location.");
out.println("<br/> ERROR: " + fne.getMessage());
}finally {
if (out != null) {
out.close();
}
if (filestream != null) {
filestream.close();
}
if (outstream != null) {
outstream.close();
}
}
}
The only issue I have is setting the file path. The path is
C:\Users\Chris\AppData\Roaming\NetBeans\7.2.1\config\GF3\domain1\
But I want it to save in
Project-war/web/images
Any ideas?
I want to make a provision to download all file types...Is there any way to download any file format in jsp...
My code snippet:
String filename = (String) request.getAttribute("fileName");
response.setContentType("APPLICATION/OCTET-STREAM");
String disHeader = "Attachment";
response.setHeader("Content-Disposition", disHeader);
// transfer the file byte-by-byte to the response object
File fileToDownload = new File(filename);
response.setContentLength((int) fileToDownload.length());
FileInputStream fileInputStream = new FileInputStream(fileToDownload);
int i = 0;
while ((i = fileInputStream.read()) != -1) {
out.write(i);
}
fileInputStream.close();
If I specify setContentType as APPLICATION/OCTET-STREAM, pdf, text, doc files are getting downloaded.... But the problem is with image files...
What is problem with image files? I want to download all image file types...
I searched similar questions but could not find proper answer...
Thanks...
Finally I somehow managed to do this...
The problem is with JSP's "Out.write", which is not capable of writing byte stream...
I replaced jsp file with servlet...
The code snippet is:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
String filename = (String) request.getAttribute("fileName");
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition",
"attachment;filename="+filename);
File file = new File(filename);
FileInputStream fileIn = new FileInputStream(file);
ServletOutputStream out = response.getOutputStream();
byte[] outputByte = new byte[(int)file.length()];
//copy binary contect to output stream
while(fileIn.read(outputByte, 0, (int)file.length()) != -1)
{
out.write(outputByte, 0, (int)file.length());
}
}
Now I can download all types of files....
Thanks for the responces :)
Check the following link ,
JSP download - application/octet-stream
Might help you to resolve the issue.
for images you should use setContentType(image/jpg).you can checkout this link for mime types
http://webdesign.about.com/od/multimedia/a/mime-types-by-content-type.htm
I have to upload some files from jsp page, when i read the inputstream for the same.
I am checking for its authenticity that its a valid file or not, for that I am using jmimemagic and it takes input stream as argument and now when I am trying to upload it, its only uploading 1 byte of data?
I feel like there is some issue with inputstream any solution pls?
//For checking the file type
InputStream loIns = aoFileStream.getInputStreamToReadFile();
byte[] fileArray = IOUtils.toByteArray(loIns);
mimeType = Magic.getMagicMatch(fileArray, true).getMimeType();
if(!loAllowedFileTypesMimeList.contains(mimeType)){
return false;
}else{
String lsFileName = aoFileStream.getFileName();
String lsFileExt = lsFileName.substring(lsFileName.lastIndexOf(".") + 1);
if(loAllowedFileTypesList.contains(lsFileExt.toLowerCase())){
return true;
}
return false;
}
// For uploading the content
File loOutputFile = new File(asFilePathToUpload);
if(!loOutputFile.exists()){
FileOutputStream loOutput = new FileOutputStream(loOutputFile);
while (liEnd != -1) {
liEnd = inputStreamToReadFile.read();
loOutput.write(liEnd);
}
inputStreamToReadFile.close();
loOutput.close();
}
In
byte[] fileArray = IOUtils.toByteArray(loIns);
you've already exhausted your inputstream, so when you want to write it to a file, you should use the content of the fileArray, not your loIns:
FileUtils.writeByteArrayToFile(loOutput, fileArray);
FileUtils is provided by apache-commons