I am trying to download xls file from a website using Htmlunit. When I click the link to download the file, I get a javascript confirm box.
I tried multiple options but not able to find the slution:
ConfirmHandler okHandler = new ConfirmHandler(){
#Override
public boolean handleConfirm(Page arg0, String arg1) {
// TODO Auto-generated method stub
return true;
}
};
webClient.setConfirmHandler(okHandler);
Also tried with
final String page = currentPage.getElementById("downloadExcel").click().getWebResponse().getContentAsString();
String buttonJavaScript = "window.location='...........'";
ScriptResult result = page.executeJavaScript(buttonJavaScript);
webClient.waitForBackgroundJavaScript(1000);
It would be really helpful if some one can suggest the solution for this.
Related
I am showing image list in a html table. I have one column in the table as image name and made it as link so user can click and download the image. The image list come from database which are saved as byte array and while sending to client side I am converting it to static object as shown below
given below
FileContent = Utilities.GetString(item.FileContent);
//GetString method
public static object GetString(byte[] bytes)
{
try
{
MemoryStream stPictureSource = new MemoryStream(bytes);
var sr = new StreamReader(stPictureSource);
return sr.ReadToEnd();
}
catch(Exception ex)
{
Logger.Log(ex);
return string.Empty;
}
}
So,Can some one have an idea, how to download image in browser.
Please let me now if the question isnt clear...
Comparison your Tags included angularjs and asp.net-web-api, This sample App showing how to do file uploads with angularjs using Asp.net Web Api. Hopefully it can aid you to deal with your problem.angular-fileupload-sample
I am trying to build an inventory management system and have recently asked a question about how to be able to store images in a package within my src file. I was told that you should not store images where class files are stored but have not been told what the best practices are for file systems. I have created a new page that allows the user to input all the data about a new part that they are adding to the system and upload an image associated with the part. When they save, everything worked fine until you try to reload the parts database. If you 'refresh' eclipse and then update the database, everything was fine because you could see the image pop into the package when refreshed. (All database info was updated properly as well.
I was told not to store these types of 'new' images with the program files but to create a separate file system to store these types of images. Is there a best practice for these types of file systems? My confusion is when the program gets saved where ever it is going to be saved, I can't have it point to an absolute path because it might not be saved on a C drive or K drive and I wouldn't want an images folder just sitting on the C drive that has all of the parts images for anyone to mess with. Please give me some good resources on how to build these file systems. I would like the images folder 'packaged' with the program when I compile it and package all the files together, I have not been able to find any good information on this, thanks!
To answer this question, probably not in the best way, but works pretty well.
I ended up making another menuItem and menu that you can see at the top 'Image Management', where it lets the user set the location that they would like to save all the images as well as a location to back up the images. it creates the directory if it is not there or it will save over the images if the directory is already there. This menu will only appear if the user has admin privileges. I would think that this could be set up with an install wizard, but I have no idea how to make one, where it only runs on installation. I am also going to add an autosave feature to save to both locations if a backup location has been set. This is the best way I can think of managing all the parts images, if anyone has some good input, please let me know. I considered a server, but think that is too much for this application and retrieving images every time the tableView populates would take a lot of time. If interested the code I used is:
public class ImageDirectoryController implements Initializable{
#FXML private AnchorPane imageDirectory;
#FXML private Label imageDirLbl, backupLbl;
#FXML private Button setLocationButton, backupButton;
#FXML private TextField imageDirPathTxtField;
Stage window;
String image_directory;
#Override
public void initialize(URL location, ResourceBundle resources) {
// TODO Auto-generated method stub
}
public void setImageDirectory(String image_address, String backup_address) {
imageDirLbl.setText(image_address);
backupLbl.setText(backup_address);
}
#FXML
public void setLocationButtonClicked () {
String imagesPath = imageDirPathTxtField.getText() + "tolmarImages\\";
File files = new File(imagesPath + "asepticImages");
File generalFiles = new File(imagesPath + "generalImages");
File facilitiesFiles = new File(imagesPath + "facilitiesImages");
boolean answer = ConfirmBox.display("Set Image", "Are you sure you want to set this location?");
if(answer) {
if (!files.exists()) {
if (files.mkdirs() && generalFiles.mkdirs() && facilitiesFiles.mkdirs()) {
JOptionPane.showMessageDialog (null, "New Image directories have been created!", "Image directory created", JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog (null, "Failed to create multiple directories!", "Image directory not created", JOptionPane.INFORMATION_MESSAGE);
}
}
DBConnection dBC = new DBConnection();
Connection con = dBC.getDBConnection();
String updateStmt = "UPDATE image_address SET image_address = ? WHERE rowid = ?";
try {
PreparedStatement myStmt = con.prepareStatement(updateStmt);
myStmt.setString(1, imageDirPathTxtField.getText());
myStmt.setInt(2, 1);
myStmt.executeUpdate();
myStmt.close();
imageDirPathTxtField.clear();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
#FXML
public void backupButtonClicked () {
String backupStatus = null;
if (backupLbl.getText().equals("")&& !imageDirPathTxtField.getText().equals("")) {
backupStatus = imageDirPathTxtField.getText();
} else if (!imageDirPathTxtField.getText().equals("")) {
backupStatus = imageDirPathTxtField.getText();
} else if (!backupLbl.getText().equals("")){
backupStatus = backupLbl.getText();
} else {
JOptionPane.showMessageDialog(null, "You must create a directory.", "No directory created", JOptionPane.INFORMATION_MESSAGE);
return;
}
boolean answer = ConfirmBox.display("Set Image", "Are you sure you want to backup the images?");
if(answer) {
DBConnection dBC = new DBConnection();
Connection con = dBC.getDBConnection();
String updateStmt = "UPDATE image_address SET image_address = ? WHERE rowid = 2";
try {
PreparedStatement myStmt = con.prepareStatement(updateStmt);
myStmt.setString(1, backupStatus);
myStmt.executeUpdate();
myStmt.close();
String source = imageDirLbl.getText() + "tolmarImages";
File srcDir = new File(source);
String destination = backupStatus + "tolmarImages";
File destDir = new File(destination);
try {
FileUtils.copyDirectory(srcDir, destDir);
JOptionPane.showMessageDialog(null, "Images copied successfully.", "Images copied", JOptionPane.INFORMATION_MESSAGE);
} catch (IOException e) {
e.printStackTrace();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
I Create an App where download a file from server in mobile, so I Use InAppBrowser plugin to open download page link, its working fine but i am not able to download file using my app, when i open download link in mobile browser its automatic start download.
please help me thanks in advance.
I think, its better to open system browser using inAppBrowser plugin for both the platform by using
window.open('http://apache.org', '_system', 'location=yes');
using this you can easily download.
InAppBrowser doesn't allow download. You will need to modify plugin to allow it for downloading.
For android, inside platforms\android\src\org\apache\cordova\inappbrowser
method name private void navigate(String url) {
include
this.inAppWebView.setDownloadListener(new DownloadListener() {
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimetype,
long contentLength) {
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
cordova.getActivity().startActivity(i);
}
});
before this line this.inAppWebView.requestFocus();
again same code in the method public void run() {
after this segment
if (clearAllCache) {
CookieManager.getInstance().removeAllCookie();
} else if (clearSessionCache) {
CookieManager.getInstance().removeSessionCookie();
}
inAppWebView.loadUrl(url);
in your .java file inside onCreate
appView.setDownloadListener(new DownloadListener() {
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimetype,
long contentLength) {
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
});
Don't know about iOS
I am creating a file that is user specific. This file is basically a results csv that is created with the option for the user to download or not. When the user leaves the page, or ends their session I want to be able to delete this file. What is the best way to handle this?
Currently I am using the File class for Java.
Thanks!
You don't have to write a file in the first place. Create the content on the fly and stream it back to the client. Wicket has a few classes in the package org.apache.wicket.request.resource to help with that.
As a starting point, look at Wicket 6 resource management and Wicket 1.5 Mounting resources
You basically mount a resource in the WicketApplication.init():
mountResource("somePath/${param1}/${param2}", new SomeResourceReference());
Than the SomeResourceReference:
public class SomeResourceReference extends ResourceReference {
#Override
public IResource getResource() {
return new SomeResource();
}
}
And finally in SomeResource:
public class SomeResource extends AbstractResource {
#Override
public AbstractResource.ResourceResponse
newResourceResponse(Attributes attributes) {
// get the parameters
PageParameters parameters = attributes.getParameters();
final String param1 = parameters.get("param1").toStringObject();
AbstractResource.ResourceResponse response
= new AbstractResource.ResourceResponse();
response.setContentType("application/CSV");
response.setCacheDuration(Duration.NONE);
response.setCacheScope(WebResponse.CacheScope.PRIVATE);
response.setContentDisposition(ContentDisposition.INLINE);
response.setWriteCallback(new AbstractResource.WriteCallback() {
#Override
public void writeData(final Attributes attributes) throws IOException {
// create your data here
attributes.getResponse().write(dataAsString);
}
});
return response;
}
}
Wicket doesn't control destroying the session. It is the concern of the servlet container you are using.
If you want to create a file in Wicket and delete the file when the session is destroyed or user want logout, it has two parts:
User logout (in Wikcet)
Store the file path or the file reference in the WebSession (Wicket)
Override the method invalidate() of your WebSession or AutheticatedWebSession, see http://ci.apache.org/projects/wicket/apidocs/6.x/org/apache/wicket/protocol/http/WebSession.html#invalidate%28%29
Session destroyed
Store the file path or the file reference into the container session and write your listener and add it to the your servlet context (e.g. tomcat using web.xml file).
See http://docs.oracle.com/javaee/7/api/javax/servlet/http/HttpSessionListener.html
I am having problems related to Tapestry on my final year project (Maven + Hibernate + Spring + Tapestry). I hope somebody could help on it.
I generate an XML file (its content is my MySql DB data in a custom format I created) on my service layer (I tried it and it is propperly generated: it is working). I tested it from my Junit tests. The problem is that I am unable to get it working from view layer, using Tapestry.
I tried this but unsuccessfully
I think that it is because file does not exist already: it is dinamically generated when user clicks on "Download XML" link.
Here you are my source code (user clicks on a link which points to this page).
POJO for the page (xmlService.exportXml is the method from my service layer which creates the XML file):
public class DownloadAll {
#Component
private Form xmlDownloadForm;
#Property
private File xmlFile;
#Property
#SessionState(create=false)
private UserSession userSession;
#Inject
private XmlService xmlService;
public StreamResponse onSubmit() {
xmlFile = xmlService.exportXml(userSession.getUserProfileId());
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime());
InputStream input = DownloadAll.class.getResourceAsStream("exportedData-"
+ userSession.getLoginName() + timeStamp + ".xml");
return new XMLAttachment(input);
}
}
And this is the page template:
<html xmlns:t="http://tapestry.apache.org/schema/tapestry_5_3.xsd"
t:type="Layout" t:pageTitle="title"
xmlns:p="tapestry:parameter"
t:menuExplanation="menuExplanation">
<form t:type="Form" t:id="xmlDownloadForm">
<input type="submit" value="${message:download}"/>
</form>
</html>
Does anybody know how to make it working? Thanks and regards.
Edit: File is generated (I can see it in the folder) when I submit the form but file is not served. I get this error instead:
org.apache.tapestry5.runtime.ComponentEventException Class
es.udc.decompras.web.pages.xml.util.XMLAttachment has been transformed
and may not be directly instantiated.
XMLAttachment is the same than JPEGAttachment.java from this link Here you are the source code:
public class XMLAttachment extends AttachmentStreamResponse {
public XMLAttachment(InputStream is, String args) {
super(is, args);
this.contentType = "application/xml";
this.extension = "xml";
}
public XMLAttachment(InputStream is) {
super(is);
this.contentType = "application/xml";
this.extension = "xml";
}
}
Only pages can be in your "pages" package. Move XMLAttachment class to any package not managed by tapestry (eg NOT base, components or pages).
Tapestry performs byte code magic on the managed packages and uses a special classloader to load them which is not compatible for utility classes etc.