Error while opening the generated PDF file with Servlets - java

By using the following code a PDF file is getting opened, I simply write the file to the servlet's output stream, but, when i am trying to open that PDF file it showing an error : "Not a pdf or Corrupted"
My code:
public void displayPj() {
String url = ficheToDisplay.getUrl();
String outPutFile = ficheToDisplay.getNom();
HttpServletResponse resp = null;
resp = (HttpServletResponse) FacesContext.getCurrentInstance()
.getExternalContext().getResponse();
File file = new File(url);
resp.reset();
resp.setHeader("Content-Disposition", "attachment; filename=\""
+ outPutFile + "\"");
resp.setContentType("application/pdf;charset=UTF-8");
resp.setHeader("Content-Length", String.valueOf(file.length()));
BufferedInputStream input = null;
BufferedOutputStream output = null;
try {
ServletOutputStream outStream = resp.getOutputStream();
input = new BufferedInputStream(new FileInputStream(file),
DEFAULT_BUFFER_SIZE);
output = new BufferedOutputStream(resp.getOutputStream(),
DEFAULT_BUFFER_SIZE);
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
int length;
while ((length = input.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
outStream.close();
} catch (Exception e) {
System.err
.println("PROBLEM STREAMING DAILY REPORT PDF THROUGH RESPONSE!"
+ e);
e.printStackTrace();
FacesMessage fm = new FacesMessage("Could Not Retrieve PDF.");
FacesContext.getCurrentInstance().addMessage(
"dailyReportArchiveFailure", fm);
}
FacesContext.getCurrentInstance().responseComplete();
}

Related

No able to download .xlsx file in jsp

i wrote my code as below for download files:
String filename = request.getParameter("file").toString();
String filepath = request.getParameter("path").toString(); ;
response.setContentType("APPLICATION/OCTET-STREAM");
response.setHeader("Content-Disposition","attachment; filename=\"" + filename + "\"");
FileInputStream fileInputStream=new FileInputStream(filepath + filename);
int i;
while ((i = fileInputStream.read()) != -1) {
out.write(i);
}
fileInputStream.close();
i was using this code in jsp page with scriplet tags ie <% %>
Now i tried it in servlet and now able to open the .xlsx file. the working code is as below:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String filename = request.getParameter("file").toString();
String filepath = request.getParameter("path").toString();
File f = new File (filepath + filename);
//set the content type(can be excel/word/powerpoint etc..)
String type = request.getParameter("type");
response.setContentType (type);
//set the header and also the Name by which user will be prompted to save
response.setHeader ("Content-Disposition", "attachment; filename=\""+filename+"\"");
//get the file name
String name = f.getName().substring(f.getName().lastIndexOf("/") + 1, f.getName().length());
//OPen an input stream to the file and post the file contents thru the
//servlet output stream to the client m/c
InputStream in = new FileInputStream(f);
try{
ServletOutputStream outs = response.getOutputStream();
int bytesRead;
byte[] buf = new byte[4 * 1024]; // 4K buffer
try {
while ((bytesRead = in.read(buf)) != -1){
outs.write(buf, 0, bytesRead);
}
} catch (IOException ioe) {
ioe.printStackTrace(System.out);
}
outs.flush();
outs.close();
in.close();
}catch(Exception e){
e.printStackTrace();
}
}

ParseException when sending an email with zip file attachment?

I am getting an Exception when sending an email with a zipped file attachment, any suggestions?
Caused by: javax.mail.internet.ParseException: Expected '/', got null
at javax.mail.internet.ContentType.(ContentType.java:102) at
javax.mail.internet.MimeBodyPart.updateHeaders(MimeBodyPart.java:1322)
at
javax.mail.internet.MimeBodyPart.updateHeaders(MimeBodyPart.java:1021)
at
javax.mail.internet.MimeMultipart.updateHeaders(MimeMultipart.java:419)
at
javax.mail.internet.MimeBodyPart.updateHeaders(MimeBodyPart.java:13
private MimeBodyPart makeZipAttachment(AttachmentInfo attachmentInfo) throws IOException, MessagingException {
ByteArrayOutputStream bos = null;
ZipOutputStream zip = null;
try
{
bos = new ByteArrayOutputStream();
zip = new ZipOutputStream(bos);
zip.putNextEntry(new ZipEntry(attachmentInfo.getName()));
InputStream inputStream = attachmentInfo.getAttachment().getInputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = inputStream.read(buffer)) != -1) {
zip.write(buffer, 0, len);
}
zip.closeEntry();
}
finally
{
if (bos != null)
bos.close();
if (zip != null)
zip.close();
}
DataSource dataSource = new ByteArrayDataSource(bos.toByteArray(), "application/zip");
MimeBodyPart mimeBodyPart = new MimeBodyPart();
mimeBodyPart.setDataHandler(new DataHandler(dataSource));
mimeBodyPart.setFileName(attachmentInfo.getName() + ".zip");
mimeBodyPart.setHeader(CONTENT_TYPE, "application/zip");
return mimeBodyPart;
}
can not say much until i run the program by myself but try with setting content as well like this mimeBodyPart.setContent

Java decompression of files from solr server

I am getting error when i am trying to decompressing the files coming from server,but i am getting error of invalid bit length in while loop.Is there any problem with code or encoding.
byte[] buffer = new byte[1024];
FileInputStream fileInput = null;
FileOutputStream fileOutputStream = null;
GZIPInputStream gzipInputStream = null;
System.out.println(source_compressed_filepath);
System.out.println(destinaton_decompressed_filepath);
try {
fileInput = new FileInputStream(source_compressed_filepath);
gzipInputStream = new GZIPInputStream(fileInput);
fileOutputStream = new FileOutputStream(destinaton_decompressed_filepath);
int len;
while ((len = gzipInputStream.read(buffer)) >=0) {
fileOutputStream.write(buffer, 0, len);
}
System.out.println("The file" + source_compressed_filepath + " was DeCompressed successfully!"
+ destinaton_decompressed_filepath);
}catch (IOException ex) {
System.out.println(" error in file decompression " + source_compressed_filepath);
} finally {
// close resources
try {
fileOutputStream.close();
gzipInputStream.close();
} catch (IOException e) {
}
}

How to upload image file to spring mvc resource folder

im working on a spring mvc project . i want to upload image and save it to resources/img/folder.
I tried below code but it does not save the image to the directory.
#Autowired
private HttpServletRequest request;
try {
// MultipartFile file = uploadItem.getFileData();
String fileName = null;
InputStream inputStream = null;
OutputStream outputStream = null;
if (multipartFile.getSize() > 0) {
inputStream = multipartFile.getInputStream();
System.out.println("File Size:::" + multipartFile.getSize());
fileName = request.getSession().getServletContext().getRealPath("/resources/") + "/students/"
+ multipartFile.getOriginalFilename();
outputStream = new FileOutputStream(fileName);
System.out.println("OriginalFilename:" + multipartFile.getOriginalFilename());
System.out.println("fileName----"+fileName);
int readBytes = 0;
byte[] buffer = new byte[10000];
while ((readBytes = inputStream.read(buffer, 0, 10000)) != -1) {
outputStream.write(buffer, 0, readBytes);
}
outputStream.close();
inputStream.close();
}
} catch (Exception e) {
e.printStackTrace();
}
Exception
11:00:39,436 INFO [stdout] (http--0.0.0.0-8080-5) File Size:::7346
11:00:39,436 ERROR [stderr] (http--0.0.0.0-8080-5) java.io.FileNotFoundException
: C:\jboss-as-7.1.1.Final\standalone\tmp\vfs\deployment65ea7dd580659db3\ObviousR
esponseWeb-1.2-SNAPSHOT.war-3a7509e73dad1cba\resources\students\zzzz.jpg (The sy
stem cannot find the path specified)
String saveDirectory=request.getSession().getServletContext().getRealPath("/")+"images\\";//to save to images folder
String fileName = multipartFile.getOriginalFilename();//getting file name
System.out.println("directory with file name: " + saveDirectory+fileName);
multipartFile.transferTo(new File(saveDirectory + fileName));

Android - file download problem - incomplete file

I have checked many code snippets, tried with and without buffer and I can't get to download whole file to SD card. The code I use currently is:
try {
url = new URL("http://mywebsite.com/directory/");
} catch (MalformedURLException e1) { }
String filename = "someKindOfFile.jpg"; // this won't be .jpg in future
File folder = new File(PATH); // TODO: add checking if folder exist
if (folder.mkdir()) Log.i("MKDIR", "Folder created");
else Log.i("MKDIR", "Folder not created");
File file = new File(folder, filename);
try {
conn = url.openConnection();
is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
FileOutputStream fos = new FileOutputStream(file);
fos.write(baf.toByteArray());
fos.close();
is.close();
} catch (IOException e) { }
This code creates directory on SD card but downloads only 77 bytes of files. What might be the problem?
The error here is that he was writing the count variable converted to byte datatype instead of the bytes read from the input stream (those should be stored in a temporary byte[] buffer via bis.read(buffer))
The proper code block should be:
BufferedInputStream bis = new BufferedInputStream(is);
FileOutputStream fos = new FileOutputStream(file);
int current = 0;
byte[] buffer = new byte[1024];
while ((current = bis.read(buffer)) != -1) {
fos.write(buffer, 0, current);
}
fos.close();
is.close();

Categories