I am using an offline application which has html,css and js files in the assets folder.When i install the application on a device a can access those files from file:////storage/emulated/0/Android/data/myapp.name/files. I need a way to hide these files at it causes a security issue. I load my app from UI webview through one of the files in assets folder
I need a way to hide these files at it causes a security issue
First, they are not files. They are assets. They are stored in the APK file, not as files on the filesystem.
Second, you cannot "hide" assets. They are in your APK, and anyone can take your APK and retrieve those assets. It is unlikely that anyone will bother to do this.
You wont be able to hide assets.
As a workaround, you can do the following:
Copy the content of your HTML, CSS and JS files in a long text String.
When app is loaded for the first time, load the string content and create a Private file at runtime and save it in Internal Storage.
Files written in Internal storage by an app can not be accessed by any other apps, including a file explorer. so they are safe from misuse.
use this code to store private file in internal storage:
String filename = "yourfile.html";
String string = "Hello world!";
FileOutputStream outputStream;
try {
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(string.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
To protect assets folder information If the html file is either css or js, the easiest way is to:
Write your code in the html editor first, and then enter it in a Java class as follows :
public class Content{
public static final String myContent ="<!DOCTYPE html> ... </html> "
And then call through the loadDataWithBaseURL method
webView.loadDataWithBaseURL(null,Content.myContent, "text/html" , "UTF-8" ,null);
And you can call js and css in html code :
...
<head>
<link rel="stylesheet" type="text/css"
href="file:///android_asset/css/custom.css" />
<script src="file:///android_asset/js/code.jquery.js"></script>
</head>
Related
My file file storage location is "E:\Records\DOCS\test.html"
How can I get Selected file path, following is my jsp tag
<form:input path="FileData" type="file"/>
I am selecting the test.html from above path and getting the selected file my model class as follows, I am able to get selected file name but along with file name I need full path.
How can I get full path in my model class ?
private CommonsMultipartFile fileData;
public CommonsMultipartFile getFileData()
{
return fileData;
}
public void setFileData(CommonsMultipartFile fileData)
{
System.out.println(fileData.getOriginalFilename()); // it gives output as test.html, I need full path
return fileData;
}
Filepaths of files selected in an <input type='file' /> tags are on the client-side. You don't need to know the filepath on the client-side, and the browser protects the client by preventing you from reading the path in any way in Javascript, and by not sending it in the request at all. All you should be concerned with is where you are going to save the file on the server-side, and you obviously would not want to save it to the same place as where it was on the client (as this would give the user the power to overwrite any file on your server they wanted). So you don't need to read any path.
This question already has answers here:
Simplest way to serve static data from outside the application server in a Java web application
(10 answers)
Closed 9 years ago.
When writing a servlet with Eclipse, where am I to put my static content (images, CSS, etc.), so that I can make my HTML link to it (e.g. <img src="http://localhost:8080/context/image.png>). I have tried putting it into the WebContent directory, but that didn't work (or I didn't know how to link to it, I tried <img src="image.png"> and also <img src="http://localhost:8080/context/image.png">).
I attached an image of my Project Explorer, so you can maybe sort it in.
To make it easier to find, here is everything I posted in comments or elsewhere:
The project's web.xml: http://pastebin.com/sTg4ugyw
My Servlet code: http://pastebin.com/az97bZAY
One of my HTML templates: http:pastebin.com/6KALf0Bw
Create a test.html file and place it at /Blog/WebContent/test.html in your Eclipse project.
<html>
<head>
<title>Test WebContent</title>
</head>
<body>
<img src="images/test.png" />
</body>
</html>
Also place a test.png image file inside the /Blog/WebContent/images folder.
Now, point your browser to http://localhost:8080/<your-web-app-name>/test.html and check if test.png gets rendered or not. If yes, then the problem lies in the way you're writing HTML output from your servlet.
For a sample ImgServlet configured as
<servlet>
<servlet-name>ImgServlet</servlet-name>
<servlet-class>pkg.path.to.ImgServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ImgServlet</servlet-name>
<url-pattern>/ImgServlet</url-pattern>
</servlet-mapping>
your doGet() method should ouput HTML as
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<html><head><title>Test WebContent</title></head>" +
"<body><img src=\"images/test.png\" /></body></html>");
EDIT: To print all the request parameters your servlet is receiving add the following just before your handleRequest() method call (which you can comment out also for testing)
PrintWriter out = response.getWriter();
Enumeration<String> parameterNames = request.getParameterNames();
while (parameterNames.hasMoreElements()) {
String param = (String) parameterNames.nextElement();
out.println(param + " = [" + request.getParameter(param) + "]");
}
Try
<img src="/context/image.png">
But it does depend on how you deploy your application. Anyways, files like images must be inside WebContent folder.
First of all, dont hard code your context in your link, it will make you hard to change the link later if your context path is changed. Instead, use EL to make the relative path:
<img src="${pageContext.request.contextPath}/img/abc.png" />
Secondly, I dont see any image in your WebContent, if you put the image manually into the window folder, you need to refresh eclipse project in order to let eclipse detects all the added files. Right click on your project in the Project Explorer and select Refresh
I have been searching this topic for quite a while, and haven't found anything that has been able to solve my problem.. so I turn to you!
I have a JSP where I open a file dialog box to select a file. Previously, I used this to upload the file to a specified directory (in my code). This works fine. I am now trying to use the same code to delete that same file by selecting it in the appropriate directory and passing it off to the servlet, which I included below. I am using the Apache Common FileUpload library to do this.
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// checks if the request actually contains upload file
if (!ServletFileUpload.isMultipartContent(request)) {
// if not, we stop here
return;
}
// configures some settings
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload delete = new ServletFileUpload(factory);
// constructs the directory path to delete file
String deletePath = UPLOAD_DIRECTORY;
// parses the request's content to extract file data
List formItems = delete.parseRequest(request);
Iterator iter = formItems.iterator();
// iterates over form's fields
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
// processes only fields that are not form fields
if (!item.isFormField()) {
String fileName = new File(item.getName()).getName();
String filePath = deletePath + File.separator + fileName;
File storeFile = new File(filePath);
//File storeFile = new File("C:\\temp\\discLogo.txt");
// deletes the file on disk
boolean erased = storeFile.delete();
}
}
UPLOAD_DIRECTORY is where I am storing my files from my upload JSP. The delete method works fine if I uncomment the line I commented out for storeFile with the hardcoded directory, as long as I select a DIFFERENT FILE in the directory initially. This leads me to believe the HttpServletRequest is holding the file in memory somewhere.
Is this correct? is there any way I can release it so I can delete the file I select initially? Or is there a much simpler way to do this?
Thanks!
The File#delete() will return false if the file does not exist at all (use File#exists() to test it beforehand), or if the file is locked because it is been opened by another app or even your own code!
Provided that this file is written do disk beforehand by your own code and guaranteed not opened elsewhere, then you should ensure that you're invoking OutputStream#close() in the finally block after writing the file's content. This problem suggests that you didn't. If you leave the file open after writing to it, then it cannot be deleted until you restart the server/JVM.
Apache Commons IO, which you should already have as a dependency of FileUpload, comes with handy utility methods reducing the file copy and close boilerplate.
InputStream input = item.getInputStream();
OutputStream output = new FileOutputStream(storeFile);
try {
IOUtils.copy(input, output);
} finally {
IOUtils.closeQuietly(output);
IOUtils.closeQuietly(input);
}
See also:
How I save and retrieve an image on my server in a java webapp.
What is the object of uploading the file? Are you going to check all the files by content?
I would say the simpler way would be to not upload the whole file. What you want to do is to call some code - JSP/Servlet -, pass as a parameter an ID of the file (most usually the path inside the server) and make it delete the file. If all the files uploaded are in the same folder, then the name should be enough (*).
After all, by uploading the file you are forcing you to have a copy in your PC of the file you want to delete (what if you deleted your local file? Should you not be able to delete the file in the server?)
(*) be sure to perform safety checks so nobody can pass ..\..\WEB-INF\web.xml as a parameter.
you can delete the file because the platform indepenedent solution is like this
File deleteFile = new File(<file Path> ) ;
// check if the file present or not
if( deleteFile.exists() )
deleteFile.delete() ;
Be carefule if the file path is directory then the directory must empty before deleting.
UploadFileorDelete
Looks like my issue was in my JSP. I had the following form initially:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>File Delete</title>
</head>
<body>
<form method="post" action="DeleteServlet"
enctype="multipart/form-data">
Select file to delete: <input type="file" name="dataFile"
id="fileChooser" /><br />
<br /> <input type="submit" value="Delete" />
</form>
</body>
</html>
I changed this by deleting encytype="multipart/form-data" from the form, and was then able to use request.getParameter("dataFile") to get the file name.
I am making a java applet which has to play video file. I have searched a code on the net but it gives an error at getParameter
Here is the code...
public void init() {
//$ System.out.println("Applet.init() is called");
setLayout(null);
setBackground(Color.white);
panel = new Panel();
panel.setLayout( null );
add(panel);
panel.setBounds(0, 0, 320, 240);
// input file name from html param
String mediaFile = null;
// URL for our media file
MediaLocator mrl = null;
URL url = null;
// Get the media filename info.
// The applet tag should contain the path to the
// source media file, relative to the html page.
// Error here: Invalid media file parameter
if ((mediaFile = getParameter("C:\\Users\\asim\\Documents\\JCreator LE\\MyProjects\\SimplePlayerApplet\\src\\Movie.avi")) == null)
Fatal("Invalid media file parameter");
try {
url = new URL(getDocumentBase(), mediaFile);
mediaFile = url.toExternalForm();
} catch (MalformedURLException mue) {
}
Here is the link to whole code :
http://docs.oracle.com/javase/1.4.2/docs/guide/plugin/developer_guide/SimplePlayerApplet.java.html
How are you 'invoking' your applet?
It seems you are trying to specify the 'parameter' as something that sits on the local file system yet you are building an 'applet' so you should really be invoking it via HTML and then pass the 'parameter in as such:
<applet code=SimplePlayerApplet.class width=320 height=300>
<param name="file" value="sun.avi">
</applet>
and thus your getParameter call should still be for "file". Just as in the code you were using before.
A couple of thoughts here:
You're using a file that reside in the local filesystem. Applets by default don't have an access to the filesystem. There is a comment above the method from the tutorial. And its clearly states the the file should be relative to html page and reside on server. Just read carefully comments there.
The example uses Applet (the class they provide extends the Applet) - its an old approach and now its deprecated. Basically what it does is uses AWT instead of newer Swing. So you should look for an example of using JApplet instead.
Hope this helps.
You should place the parameter in HTMLpart, this would make the applet independend from the content. You confused the parameter name with its value.
<HTML> <BODY>
<APPLET CODE="SimplePlayerApplet.class" WIDTH=320 HEIGHT=240>
<PARAM NAME="filename" VALUE="C:\\Users\\asim\\Documents\\JCreator LE\\MyProjects\\SimplePlayerApplet\\src\\Movie.avi">
</APPLET>
</BODY> </HTML>
if ((mediaFile = getParameter("filename")) == null)
...
In order to access the filesystem you need to sign the applet.
The Line:
URL(getDocumentBase(), mediaFile);
tries to open the mediaFile relative from DocumentBase. This means relative to the URL of the document in which this applet is embedded.
See alse Applet.
Thus the easiest way to get it run would be to copy your Movie.avi in the same folder where your HTML-File resides and use
URL(getDocumentBase(), "Movie.avi");
After that you should make it configurable by supplying the filename as a parameter.
Using Java, I need to save a complete webpage(with all its contents like images, css, javascript e.t.c) like how we can do with save as-->complete webpage option with HttpClient lib. How can I do this?
You can try lib curl java
http://curl.haxx.se/libcurl/java/
And you can refer to this discussion also
curl-equivalent-in-java
You have to write an application that fetches the html file, parses it and extracts all the references, and then fetches all the files found by parsing.
It's not so easy because some CSS/JS/Images files paths might be "hidden". Just consider the following example:
<script type="...">
document.write("&bla;script" + " type='...' src='" + blahBlah() + "'&bla;" + "&bla;/script&bla;");
</script>
However, fetching page source, parsing in the search for URLs and downloading founded URLs is pretty everything you'll probably need.