How to Download the file to desktop in java - java

I am trying to to download the report generated in server to the local machine for that i have written a servlet and calling the servelt from my jsp. But its not ont invoking my servlet... i have added some S.O.P for testing and i am not getting those s.o.ps in log and and the screen display blank.
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
System.out.println("In RRR DownLoadServlet");
outs = response.getOutputStream();
String action = request.getParameter("action");
String strInfodom = "DMINFO88";
//String filename = request.getParameter("filename");
String filename = "/Report_Income Statement.xls";
if (action.equals("6")) {
Vector<String> vProperties = new Vector<String>();
vProperties.addElement("DOCUMENT_UPLOAD_SAVE");
vProperties.addElement("DOCUMENT_UPLOAD_TEMP");
// Properties prop = SMSServices.getConfiguration(vProperties);
// String strUploadSave = (String) prop.get("DOCUMENT_UPLOAD_SAVE");
// String strUploadTemp = (String) prop.get("DOCUMENT_UPLOAD_TEMP");
String completePath = RRRConstants.RRR_PATH+RRRConstants.OUTPUT;
System.out.println("Report File path :::::::::::::::: "+completePath);
if (completePath != null) {
byte arrByte[] = new byte[1024];
int readBytes = -1;
response.setContentType("application/x-download");
response.setHeader("Content-Disposition", "attachment; filename=" + completePath.substring(completePath.lastIndexOf("/") + 1));
fin = new FileInputStream(new File(completePath));
BufferedInputStream bout = new BufferedInputStream(fin);
while ((readBytes = bout.read(arrByte)) > 0) {
outs.write(arrByte, 0, readBytes);
}
outs.flush();
}
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
try {
if (outs != null)
outs.close();
if (fin != null)
fin.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
jsp code :
<%
String infodom = request.getParameter("infodom");
String user = (String) session.getAttribute("gsUsrID");
String strURL = "";
FileHandler objFileHandler = new FileHandler(null);
WebServerInfo objWebServer = objFileHandler.getPrimaryWebServerInfo();
String protocol = objWebServer.getServletProtocol();
try
{
strURL = protocol+ "://" + getServletConfig().getServletContext().getInitParameter("FIC_WEBSERVER_IP") + ":" + getServletConfig().getServletContext().getInitParameter("FIC_WEBSERVER_PORT") + request.getContextPath() + "/RRRDownLoadServlet?infodom="+infodom+"&filename=";
}
catch(Exception e)
{
System.out.println(" [Download.jsp] Exception "+e);
}
%>
function downloareport()
{
alert("downloading");
var filename = "/Report_Income Statement.xls";
downloadExcel(filename);
}
function downloadExcel(excelFile)
{
window.location.href = "<%=strURL%>"+ excelFile+"&mode=excel";
}

The jsp code contains some javascript. Check these points:
In javascript; writing just function body doesn't automatically invoke that, one has to make call to the function somewhere.
Also tags for java-scripts seems missing.

The request from the JSP is get, not post. Use doGet(...){} instead of doPost(...){...} in servlet.

Related

Uploading an Image to a restful webservice produces an unviewable image

I'm using the following solution to try and receive an image in a restful webservice written in java:
#POST
#Consumes(MediaType.MULTIPART_FORM_DATA)
#Produces(MediaType.TEXT_PLAIN)
public String getFile(#FormDataParam("pic") InputStream file,
#QueryParam("uid") String uid) {
try {
storeFile(file, uid);
} catch (IOException ex) {
Logger.getLogger(UploadImage.class.getName()).log(Level.SEVERE, null, ex);
return "failed";
}
return "success";
}
private void storeFile(InputStream input, String uid) throws IOException {
String absPath = PATH_TO_FILES + uid + ".jpg";
try {
OutputStream out = new FileOutputStream(new File(absPath));
int read = 0;
byte[] bytes = new byte[1024];
out = new FileOutputStream(new File(absPath));
while ((read = input.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Here is the client code (javascript):
$scope.fileSelect = function (files) {
var file = files[0];
console.log("File loaded");
console.log(files);
console.log('uid = ' + $scope.uid + ' user = ' + $scope.user);
var formData = new FormData();
formData.append('pic', file);
var requestBody = {"token": $scope.token};
var req = {
method: 'POST',
url: 'http://192.168.0.9/resources/UploadPicture?uid=' + $scope.uid,
headers: {
'Content-Type': undefined
},
data: formData
};
console.log(FormData);
$http(req).then(function(response){
console.log(response);
}, function(error){
console.log(error);
});
};
This code produces a file that isnt viewable. The files im expecting are images.
So i got 2 questions:
Whenever the webservice gets called an a response is return, it seems like the image isnt fully flushed to the harddisk. After a while i can edit it. Is there a way to respond back to the client when the image is actually flushed to the disk?
How can i get the input stream to produce a viewable image when its written to the disk?
--edit--
After some fiddling with the file, i realized if i edit the image in notepad++ and took off the beggining and ending tags for the form boundaries, the image is viewable again:
Produced File
Is there a way for the form boundaries to stop interfering with the image data?
I found a solution using apache commons fileupload:
#POST
#Consumes(MediaType.MULTIPART_FORM_DATA)
#Produces(MediaType.TEXT_PLAIN)
public String getFile(#Context HttpServletRequest request, #QueryParam("uid") String uid) {
ServletFileUpload upload = new ServletFileUpload();
try {
FileItemIterator iter = upload.getItemIterator(request);
while (iter.hasNext()) {
FileItemStream item = iter.next();
String name = item.getFieldName();
InputStream stream = item.openStream();
if (item.isFormField()) {
System.out.println("Form field " + name + " with value "
+ Streams.asString(stream) + " detected.");
} else {
System.out.println("File field " + name + " with file name "
+ item.getName() + " detected.");
// Process the input stream
storeFile(stream, uid);
}
}
return "success";
} catch (FileUploadException ex) {
Logger.getLogger(UploadImage.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(UploadImage.class.getName()).log(Level.SEVERE, null, ex);
}
return "failed.";
}

Uploading file using Java Servlet [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I have a Servlet that uploads an image, and saves the path in a MySQL db. I use the same code for another image upload on a different jsp page, and I get a null pointer exception on "getFileName();"
I do not see any difference in this code. Please help:
addlientimage.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, ClassNotFoundException, SQLException {
response.setContentType("text/html;charset=UTF-8");
String name = request.getParameter("clientname");
String id = request.getParameter("clientid");
String password = request.getParameter("clientpassword");
String email = request.getParameter("clientemail");
final String path = getServletContext().getRealPath("/imgs");
final Part filePart = request.getPart("imageurl");
final String fileName = getFileName(filePart);
String url = "imgs/" + fileName;
OutputStream outStream;
outStream = null;
InputStream filecontent = null;
final PrintWriter writer = response.getWriter();
response.sendRedirect("clients.jsp");
try {
outStream = new FileOutputStream(new File(path + File.separator
+ fileName));
filecontent = filePart.getInputStream();
int read = 0;
final byte[] bytes = new byte[1024];
while ((read = filecontent.read(bytes)) != -1) {
outStream.write(bytes, 0, read);
}
Mysqlconnector dbconnect = new Mysqlconnector();
/* TODO output your page here. You may use following sample code. */
try (PreparedStatement clientinfo = dbconnect.getConnection().prepareStatement("INSERT INTO clients VALUES ( ?, ?, ?, ?, ? )")) {
clientinfo.setString(1, id);
//setting the first placeholder to the password recieved from the client
clientinfo.setString(2, password);
clientinfo.setString(3, name);
clientinfo.setString(4, url);
clientinfo.setString(5, email);
clientinfo.executeUpdate();
String clients = new PopulateClientsTable().getClientRows();
HttpSession session = request.getSession();
session.setAttribute("clients", clients);
}
} catch (FileNotFoundException fne) {
writer.println("You either did not specify a file to upload or are "
+ "trying to upload a file to a protected or nonexistent "
+ "location.");
writer.println("<br/> ERROR: " + fne.getMessage());
} finally {
if (outStream != null) {
outStream.close();
}
if (filecontent != null) {
filecontent.close();
}
if (writer != null) {
writer.close();
}
}
}
private String getFileName(final Part part) {
final String partHeader = part.getHeader("content-disposition");
for (String content : part.getHeader("content-disposition").split(";")) {
if (content.trim().startsWith("filename")) {
return content.substring(
content.indexOf('=') + 1).trim().replace("\"", "");
}
}
return null;
}
addmanager.java
response.setContentType("text/html;charset=UTF-8");
String personName = request.getParameter("mediapersonname");
String productName = request.getParameter("productname");
String mediainfoid = request.getParameter("mediainfoid");
String mediaAbout = request.getParameter("mediaabout");
String personAbout = request.getParameter("personabout");
String productAbout = request.getParameter("productabout");
final String path = getServletContext().getRealPath("/imgs");
final Part filePart = request.getPart("personurl");
final String fileName = getFileName(filePart);
String url = "imgs/" + fileName;
OutputStream outStream;
outStream = null;
InputStream filecontent = null;
final PrintWriter writer = response.getWriter();
response.sendRedirect("adminmediainfo.jsp");
try {
outStream = new FileOutputStream(new File(path + File.separator
+ fileName));
filecontent = filePart.getInputStream();
int read = 0;
final byte[] bytes = new byte[1024];
while ((read = filecontent.read(bytes)) != -1) {
outStream.write(bytes, 0, read);
}
Mysqlconnector dbconnect = new Mysqlconnector();
/* TODO output your page here. You may use following sample code. */
try (PreparedStatement clientinfo = dbconnect.getConnection().prepareStatement("INSERT INTO mediainfo VALUES ( ?, ?, ?, ?, ?, ?, ? )")) {
//setting the first placeholder to the password recieved from the client
clientinfo.setString(1, mediainfoid);
clientinfo.setString(2, mediaAbout);
clientinfo.setString(3, personName);
clientinfo.setString(4, productName);
clientinfo.setString(5, productAbout);
clientinfo.setString(6, personAbout);
clientinfo.setString(7, url);
clientinfo.executeUpdate();
String clients = new PopulateMediaInfoTable().getClientRows();
HttpSession session = request.getSession();
session.setAttribute("mediainfo", clients);
}
} catch (FileNotFoundException fne) {
writer.println("You either did not specify a file to upload or are "
+ "trying to upload a file to a protected or nonexistent "
+ "location.");
writer.println("<br/> ERROR: " + fne.getMessage());
} finally {
if (outStream != null) {
outStream.close();
}
if (filecontent != null) {
filecontent.close();
}
if (writer != null) {
writer.close();
}
}
}
private String getFileName(final Part part) {
final String partHeader = part.getHeader("content-disposition");
for (String content : part.getHeader("content-disposition").split(";")) {
if (content.trim().startsWith("filename")) {
return content.substring(
content.indexOf('=') + 1).trim().replace("\"", "");
}
}
return null;
}
The code for addclientimage.java works. The code for addmanager.java does not.
ERROR LOG
type Exception report
message
description The server encountered an internal error that prevented it from fulfilling this request.
exception
java.lang.NullPointerException
AddMediaInfo.getFileName(AddMediaInfo.java:115)
AddMediaInfo.processRequest(AddMediaInfo.java:53)
AddMediaInfo.doPost(AddMediaInfo.java:158)
javax.servlet.http.HttpServlet.service(HttpServlet.java:644)
javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
note The full stack trace of the root cause is available in the Apache Tomcat/8.0.15 logs.
I find just two possible reasons for getFileName to throw a NPE:
final String partHeader = part.getHeader("content-disposition");
for (String content : part.getHeader("content-disposition").split(";")) {
Either part is null, so you have to ensure that the caller method is not passing a null to getFileName. I.E.: There exists a "personurl" part within the input request.
Wither partHeader is null, so you have to ensure that the client is actually including a "content-disposition" header within the sent request.

How to return back or call signed applet's method from server side controller?

My download scenario is: when i click on download link on jsp it calls signed applet method with file's id, from applet I call server side method by passing that id. I can get that file at server side but I want to return/pass that file back to my applet function.
My question is how to return back or pass downloaded file to my applet?
Or How can I set a file to response object at server side that can be useful at applet?
My Signed Applet :
private static void downloadEncryptedFile(String uuid) throws HttpException, IOException {
String uri = "http://localhost:8080/encryptFileDownload.works?uuid="+uuid;
HttpClient client = new HttpClient();
PostMethod postMethod = new PostMethod(uri);
postMethod.setRequestHeader("Content-type", "text/xml; charset=ISO-8859-1");
client.executeMethod(postMethod);
postMethod.releaseConnection();
}
My Server side function:
#RequestMapping(value = "/encryptFileDownload/{uuid}.works", method = RequestMethod.POST)
public String downloadEncryptFile(#PathVariable("uuid") String uuid, HttpSession session, HttpServletResponse response) {
try {
if (StringUtils.isNotEmpty(uuid)) {
LOG.info("-----UUID----");
Node node = contentRetrieveService.getByNodeId(uuid);
Node resource = node.getNode("jcr:content");
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment; filename=\"" + node.getName() + "\"");
InputStream in = resource.getProperty("jcr:data").getBinary().getStream();
ServletOutputStream outs = response.getOutputStream();
int i = 0;
while ((i = in.read()) != -1) {
outs.write(i);
}
outs.flush();
outs.close();
in.close();
LOG.info("File Downloaded");
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
I got the solution; I just wanted to pass a file id download it and return that file back to my applet, hence I have made changes in my code as:
My Applet:
try {
URL urlServlet = new URL("uri for your servlet");
URLConnection con = urlServlet.openConnection();
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false);
con.setRequestProperty(
"Content-Type",
"application/x-java-serialized-object");
// send data to the servlet
OutputStream outstream = con.getOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(outstream);
oos.writeObject(uuid);
oos.flush();
oos.close();
// receive result from servlet
InputStream instr = con.getInputStream();
ObjectInputStream inputFromServlet = new ObjectInputStream(instr);
String name = con.getHeaderField("filename");
File fi = new File(name);
int i = 0;
while ((i = inputFromServlet.read()) != -1) {
System.out.println(inputFromServlet.readLine());
}
inputFromServlet.close();
instr.close();
} catch (Exception ex) {
ex.printStackTrace();
}
Server side Function just replace with this:
OutputStream outs = response.getOutputStream();
outputToApplet = new ObjectOutputStream(outs);
int i = 0;
while ((i = in.read()) != -1) {
outputToApplet.write(i);
}

Downloaded File Size 0

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
}

Programmatically downloading files pushed through a PHP page

Some PHP sites use a page to act as a middle man for handling file downloads.
With a browser this works transparently. There seems to a be a slight pause while the php page processes the request.
However, attempting a download through Java using a URL or HttpURLConnection returns a plain html page. How could I get the file downloads working in the same way?
Edit: Here is an example link:
http://depot.eice.be/index.php?annee_g=jour&cours=poo
Edit: Here is some of the code I've been testing:
// This returns an HTML page
private void downloadURL(String theURL) {
URL url;
InputStream is = null;
DataInputStream dis;
String s;
StringBuffer sb = new StringBuffer();
try {
url = new URL(theURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.connect();
if (conn.getResponseCode()!=HttpURLConnection.HTTP_OK)
return;
InputStream in = conn.getInputStream();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int i;
while ((i = in.read()) != -1) {
bos.write(i);
}
byte[] b = bos.toByteArray();
FileOutputStream fos = new FileOutputStream( getNameFromUrl( theURL ) );
fos.write(b);
fos.close();
conn.disconnect();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// This will throw Exceptions if the URL isn't in the expected format
public String getNameFromUrl(String url) {
int slashIndex = url.lastIndexOf('/');
int dotIndex = url.lastIndexOf('.');
System.out.println("url:" + url + "," + slashIndex + "," + dotIndex);
if (dotIndex == -1) {
return url.substring(slashIndex + 1);
} else {
try {
return url.substring(slashIndex + 1, url.length());
} catch (StringIndexOutOfBoundsException e) {
return "";
}
}
}
Considering no other constrains, you can read the redirected URL from the HTTP header and connect to that URL directly from JAVA.
There is an API setting to follow redirects automatically – but it should be true by default. How do you access the URL?
See Java API docs...
I think I've found a solution using HttpUnit. The source of the framework is available if you wish to see how this is handled.
public void downloadURL(String url) throws IOException {
WebConversation wc = new WebConversation();
WebResponse indexResp = wc.getResource(new GetMethodWebRequest(url));
WebLink[] links = new WebLink[1];
try {
links = indexResp.getLinks();
} catch (SAXException ex) {
// Log
}
for (WebLink link : links) {
try {
link.click();
} catch (SAXException ex) {
// Log
}
WebResponse resp = wc.getCurrentPage();
String fileName = resp.getURL().getFile();
fileName = fileName.substring(fileName.lastIndexOf("/") + 1);
System.out.println("filename:" + fileName);
File file = new File(fileName);
BufferedInputStream bis = new BufferedInputStream(
resp.getInputStream());
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream(file.getName()));
int i;
while ((i = bis.read()) != -1) {
bos.write(i);
}
bis.close();
bos.close();
}
System.out.println("Done downloading.");
}

Categories