I am working on a jsp zip file download ,I am able to download the file but while extracing I get Invalid zip file error. In the java controller I have added
#RequestMapping("/upload")
public void getDownload(ModelView mv,HttpServletResponse response)
{
String fileName = "";
String fullZipFileName = zipDir+ zipFileName;
FileManager fm = FileManager.getInstance();
zipOS = fm.getZipOutputStream(fullZipFileName);
try {
for(int i = 0; i < numOfFiles; i++) {
fileName = (String) selectedFiles.get(i);
File file = new File(directory, fileName);
bIS = fm.getBufferedInputStream(file.getAbsolutePath());
ZipEntry entry = new ZipEntry(file.getName());
zipOS.putNextEntry(entry);
while((count = bIS.read(fileToAddToZip, 0, buffer)) != -1) {
zipOS.write(fileToAddToZip, 0, count);
}
bIS.close();
}
zipOS.close();
FileManager fm = FileManager.getInstance();
bIS = fm.getBufferedInputStream(zipFileName);
byte[] byteArray = new byte[bIS.available()];
bIS.read(byteArray);
bIS.close();
response.setContentType("application/octate-stream");
response.setHeader("Content-Disposition", "attachment;filename" + zippedFilename);
response.getOutputStream().write(byteArray);
}
In the jsp side I have added
$.ajax({
type: 'POST',
url: "${pageContext.request.contextPath}/download",
contentType: "application/json",
data: JSON.stringify(payload),
success: function (res, textStatus, response) {
var fileName = response.getResponseHeader("content-disposition").replace("attachment;filename=", "");
var fileName = response.getResponseHeader("Content-Disposition").replace("attachment;filename=", "");
var bytes = new Uint8Array(res.length);
for(var i=0;i< res.length;i++)
{
var as=res.charCodeAt(i);
bytes[i]=as;
}
var blob = new Blob([bytes], { type: "application/octetstream" });
//Check the Browser type and download the File.
var isIE = false || !!document.documentMode;
if (isIE) {
window.navigator.msSaveBlob(blob, fileName);
} else {
var url = window.URL || window.webkitURL;
link = url.createObjectURL(blob);
var a = $("<a />");
a.attr("download", fileName);
a.attr("href", link);
$("body").append(a);
a[0].click();
$("body").remove(a);
}
},
error: function (e) {
}
});
I am able to download the file but when I try to extract the zip file ,I get Invalid zip file. Can someone tell me how can I fix this issue
Related
I'm trying to open a pdf file in which has been exported from a repository. Here is the code that I'm using:
ConnectionManager con = new ConnectionManager();
String id = request.getParameter("uname");
String objname = request.getParameter("pass");
Properties prop = new Properties();
//ResourceBundle resource = ResourceBundle.getBundle("query");
//prop.load(getClass().getResourceAsStream("query.properties"));
String uname = "DmAdmin";
String pass = "<pass>";
String docbase = "QDocs";
String ext = new String();
IDfSession ssn = con.getSession(uname, pass, docbase);
sysObj = (IDfSysObject)ssn.getObject((IDfId)new DfId(id));
//ByteArrayInputStream buf = sysObj.getContent();
//sysObj.getFile("C:\\Users\\rsaha04\\Downloads\\"+objname+".pdf");
String path = "C:\\Users\\rsaha04\\Downloads\\";
String filename = path + sysObj.getObjectName().toString();
IDfCollection coll = sysObj.getRenditions(null);
if (coll != null)
{
while (coll.next())
{
String format = coll.getString("full_format");
{
if (format.equalsIgnoreCase("pdf"))
{
ext = "pdf";
System.out.println("extension set: "+ext);
}
}
}
filename = filename+"."+ext;
sysObj.getFileEx(filename, ext, 0, false);
}
con.closeConnection(ssn);
//Process p = Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler "+filename);
response.setContentType("application/pdf");
response.setHeader("Content-Disposition", "inline; filename='"+filename+"'");
I'm able to open the pdf file in adobe acrobat reader but it is failing for browser with this error.
Please help me understand where I'm going wrong here.
You need your server to respond with a pdf file. You set the response headers, but your code never writes the pdf data into the response.
Do that using
response.write(bytesFromPdfFile)
This is the code in Java Class.
redflaglight.png image is present in the Images folder
file not found Null pointer exception is at
inputStream = new FileInputStream(path);
Struts2.3.5 Java7
public String createRootPath() throws UnsupportedEncodingException {
String rootPath = "";
String path = ExportExcelBusiness.class.getProtectionDomain()
.getCodeSource().getLocation().getPath();
File f = new File(path);
String ff = f.getParent();
f = new File(ff);
ff = f.getParent();
f = new File(ff);
ff = f.getParent();
f = new File(ff);
ff = f.getParent();
f = new File(ff);
ff = f.getParent();
f = new File(ff);
ff = f.getParent();
f = new File(ff);
ff = f.getParent();
String decodedPath = URLDecoder.decode(ff, "UTF-8");
rootPath = decodedPath.replace('\\', '/');
rootPath += "/WebContent/pages/appsresponse/images";
return rootPath;
}
path = createRootPath()+ "/up_arrow_export.png";
InputStream inputStream = null;
int pictureIdx = 0;
byte[] bytes;
try {
inputStream = new FileInputStream(path);
bytes = IOUtils
.toByteArray(inputStream);
pictureIdx = wb.addPicture(bytes,
Workbook.PICTURE_TYPE_PNG);
} finally {
if (inputStream != null) {
inputStream.close();
}
}
Though File is present in the path, unable to fetch that file. This started after upgrading from Struts2.2.1 to struts2.3.5
If you are running this code on server and using relative path then, your file should be inside server directory. like:-
your_server_path/pages/appsresponse/images
Problem is you are keeping your images in workspace, you need to keep that in server directory.
EDIT
Verify your path
File file=new File(path);
System.out.print(file.getAbsolutePath()); //check whether file is present at this path or not
As per my requirement,i need to download a file from mail inbox into a specified directory,later after some time if same comes in , i need to save the same file into the same directory but with different name,here previous file should not be overridden means files must be saved in the same directory with same names(here i have one assumption,that , for example if my file is abc.txt, after modifications if i download the modified file it can be saved as abc(1).txt ). how can i resolve my issue? can anybody assist me to come out from this issue in JAVA. Below is my code but it is overwriting same file.
if (contentType.contains("multipart")) {
// this message may contain attachment
Multipart multiPart = (Multipart) message.getContent();
for (int i = 0; i < multiPart.getCount(); i++) {
MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(i);
if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) {
// save an attachment from a MimeBodyPart to a file
String destFilePath = "F:/unprocessed/"+part.getFileName();
InputStream input = part.getInputStream();
BufferedInputStream in = null;
in = new BufferedInputStream(input);
FileOutputStream output = new FileOutputStream(destFilePath);
byte[] buffer = new byte[4096];
int byteRead;
while ((byteRead = input.read(buffer)) != -1) {
output.write(buffer, 0, byteRead);
}
System.out.println("FileOutPutStream is Being Closed");
output.close();
}
}
}
As said before, you need to check the existing files. Here's one way of doing that:
public String getUniqueFileName(String input) {
String base = "F:/unprocessed/";
String filename = base+input;
File file = new File(filename);
int version = 0;
while (file.exists()) {
version++;
String filenamebase = filename.substring(0, filename.lastIndexOf('.'));
String extension = filename.substring(filename.lastIndexOf('.'));
file = new File(filenamebase+"("+ version+")"+extension);
}
return file.getAbsolutePath();
}
Then change the assignment of destFilePath to a call this method:
String destFilePath = getUniqueFileName(part.getFileName());
I am uploading a file using Servlet using the code as follows::
FileItem fi = (FileItem) i.next();
String fileName = fi.getName();
out.print("FileName: " + fileName);
String contentType = fi.getContentType();
boolean isInMemory = fi.isInMemory();
long sizeInBytes = fi.getSize();
if (fileName == null || fileName == "") {
resumefilepath = "";
} else {
resumeflag = 1;
if (fileName.lastIndexOf("\\") >= 0) {
file = new File(resumePath + fileName.substring(fileName.lastIndexOf("\\")));
} else {
file = new File(resumePath + fileName.substring(fileName.lastIndexOf("\\") + 1));
}
fi.write(file);
What I am getting is my file is getting uploaded correctly. I needed to upload my file with different name, but make sure that file content should not be changed. Suppose I am having an image 'A.png' then it should be saved as 'B.png'. Please help guys?? I have tried like this:
File f1 = new File("B.png");
// Rename file (or directory)
file.renameTo(f1);
fi.write(file);
But not working
Assuming that you are referring to the Apache Commons FileItem you are simply in control what File instance you pass to FileItem.write. At that point, the File object is just an abstract name and the file will be created by that method.
It is your code which reads the name from the FileItem and constructs a File object with the same name. You don’t have to do it. So when you pass new File("B.png") to the write method of a FileItem representing an upload of A.png the contents will be save in a file B.png.
E.g. to do literally what you asked for you can change the line
fi.write(file);
to
if(file.getName().equals("A.png")) file=new File(file.getParentFile(), "B.png");
fi.write(file);
A simplified version of your code may look like:
String fileName = fi.getName();// name provided by uploader
if (fileName == null || fileName == "") {
resumefilepath = "";
} else {
// convert to simple name, i.e. remove any prepended path
fileName = fileName.substring(fileName.lastIndexOf(File.separatorChar)+1);
// your substitution:
if(fileName.equalsIgnoreCase("A.png")) fileName="B.png";
// construct File object
file = new File(resumePath, fileName);
// and create/write the file
fi.write(file);
}
If you are looking for an answer where you can upload file and change name and insert it into database here it is
<%
File file ;
int maxFileSize = 5000 * 1024;
int maxMemSize = 5000 * 1024;
ServletContext context = pageContext.getServletContext();
String filePath = "/NVS_upload/NVS_school_facilities_img/";
String title=null,description=null,facility_id=null;
ArrayList<String> imagepath=new ArrayList<String>();
String completeimagepath=null;
// Verify the content type
String contentType = request.getContentType();
int verify=0;
//String school_id=null;
String exp_date=null;
String rel_date=null;
int school_id=0;
String title_hindi=null;
String description_hindi=null;
if ((contentType.indexOf("multipart/form-data") >= 0)) {
DiskFileItemFactory factory = new DiskFileItemFactory();
// maximum size that will be stored in memory
factory.setSizeThreshold(maxMemSize);
// Location to save data that is larger than maxMemSize.
factory.setRepository(new File("c:\\temp"));
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// maximum file size to be uploaded.
upload.setSizeMax( maxFileSize );
try {
// Parse the request to get file items.
List fileItems = upload.parseRequest(request);
// Process the uploaded file items
Iterator i = fileItems.iterator();
while ( i.hasNext () ) {
FileItem fi = (FileItem)i.next();
if ( !fi.isFormField () ) {
// Get the uploaded file parameters
String fieldName = fi.getFieldName();
String fileName = fi.getName();
boolean isInMemory = fi.isInMemory();
long sizeInBytes = fi.getSize();
//this genrates unique file name
String id = UUID.randomUUID().toString();
//we are splitting file name here such that we can get file name and extension differently
String[] fileNameSplits = fileName.split("\\.");
// extension is assumed to be the last part
int extensionIndex = fileNameSplits.length - 1;
// add extension to id
String newfilename= id + "." + fileNameSplits[extensionIndex];
//File newName = new File(filePath + "/" +);
//this stores the new file name to arraylist so that it cn be stored in database
imagepath.add(newfilename);
File uploadedFile = new File(filePath , newfilename);
fi.write(uploadedFile);
out.println("Uploaded Filename: " + filePath +
newfilename + "<br>");
}
else if (fi.isFormField()) {
if(fi.getFieldName().equals("title"))
{
title=fi.getString();
out.println(title);
}
if(fi.getFieldName().equals("description"))
{
description=fi.getString();
//out.println(description);
}
if(fi.getFieldName().equals("activity_name"))
{
facility_id=fi.getString();
//out.println(facility_id);
}
if(fi.getFieldName().equals("rel_date"))
{
rel_date=fi.getString();
//out.println(school_id);
}
if(fi.getFieldName().equals("exp_date"))
{
exp_date=fi.getString();
// out.println(school_id);
}
if(fi.getFieldName().equals("school_id"))
{
school_id=Integer.valueOf(fi.getString());
// out.println(school_id);
}
if(fi.getFieldName().equals("title-hindi"))
{
title_hindi=fi.getString();
// out.println(school_id);
}
if(fi.getFieldName().equals("description-hindi"))
{
description_hindi=fi.getString();
out.println(school_id);
}
}
}
out.println("</body>");
out.println("</html>");
} catch(Exception ex) {
out.println(ex);
}
}
else {
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet upload</title>");
out.println("</head>");
out.println("<body>");
out.println("<p>No file uploaded</p>");
out.println("</body>");
out.println("</html>");
}
%>
<%
try{
completeimagepath=imagepath.get(0)+","+imagepath.get(1)+","+imagepath.get(2);
Connection conn = null;
Class.forName("org.postgresql.Driver").newInstance();
conn = DriverManager.getConnection(
"connection url");
PreparedStatement ps=conn.prepareStatement("INSERT INTO activities_upload (activity_name,title,description,pdfname,publish_date,expiry_date,title_hindi,description_hindi,school_id) VALUES(?,?,?,?,?,?,?,?,?)");
ps.setString(1,facility_id);
ps.setString(2,title);
ps.setString(3,description);
ps.setString(4,completeimagepath);
ps.setDate(5,java.sql.Date.valueOf(rel_date));
ps.setDate(6,java.sql.Date.valueOf(exp_date));
ps.setString(7,title_hindi);
ps.setString(8,description_hindi);
ps.setInt(9,school_id);
verify=ps.executeUpdate();
}
catch(Exception e){
out.println(e);
}
if(verify>0){
HttpSession session = request.getSession(true);
session.setAttribute("updated","true");
response.sendRedirect("activitiesform.jsp");
}
%>
I have tried to extract Lotus Notes database icon by using DXL Exporter but it is not success. Result file is corrupt and can not be opened by image viewer.
How can I extract Lotus Notes database icon by using java?
private String extractDatabaseIcon() {
String tag = "";
String idfile = "";
String password = "";
String dbfile = "";
NotesThread.sinitThread();
Session s = NotesFactory.createSessionWithFullAccess();
s.createRegistration().switchToID(idfile, password);
Database d = s.getDatabase("", dbfile);
NoteCollection nc = d.createNoteCollection(false);
nc.setSelectIcon(true);
nc.buildCollection();
String noteId = nc.getFirstNoteID();
int counter = 0;
while (noteId != null) {
counter++;
try {
Document doc = d.getDocumentByID(noteId);
DxlExporter dxl = s.createDxlExporter();
String xml = dxl.exportDxl(doc);
xml = xml.substring(xml.indexOf("<note "));
org.jsoup.nodes.Document jdoc = Jsoup.parse(xml);
Element ele = jdoc.select("rawitemdata").first();
String raw = ele.text().trim();
String temp = System.getProperty("java.io.tmpdir") + UUID.randomUUID().toString() + "\\";
File file = new File(temp);
file.mkdir();
String filename = temp + UUID.randomUUID().toString().replaceAll("-", "") + ".gif";
byte[] buffer = decode(raw.getBytes());
FileOutputStream fos = new FileOutputStream(filename);
fos.write(buffer);
fos.close();
tag = filename;
} catch (Exception e) {
logger.error("", e);
}
if (counter >= nc.getCount()) {
noteId = null;
} else {
noteId = nc.getNextNoteID(noteId);
}
}
return tag;
}
private byte[] decode(byte[] b) throws Exception {
ByteArrayInputStream bais = new ByteArrayInputStream(b);
InputStream b64is = MimeUtility.decode(bais, "base64");
byte[] tmp = new byte[b.length];
int n = b64is.read(tmp);
byte[] res = new byte[n];
System.arraycopy(tmp, 0, res, 0, n);
return res;
}
It is not even a bitmap, it is an icon. The format you can find here:
http://www.daubnet.com/formats/ICO.html
I managed to do this, a long time ago, in LotusScript. My code was based on an earlier version of this page:
http://www2.tcl.tk/11202
For the icon itself, you only have to open one document:
NotesDocument doc = db.getDocumentByID("FFFF8010")
exporter = session.createDXLExporter
exporter.setConvertNotesBitmapsToGIF(false)
outputXML = exporter.export(doc)
and then parse the XML to find the rawitemdata from the IconBitmap item, as you did in your original code.
I'm not sure what the format is. As far as I know' it's a 16 color bitmap, but not in standard BMP file format. And it's definitely not GIF format, but you can tell the DXLExporter to convert it. The default is to leave it native, so you need to add this to your code before you export:
dxl.setConvertNotesBitmapsToGIF(true);