How to download file using dropbox - java

I'm trying to build an app that gives my users right to download file from my dropbox storage.
So I've got next quesions:
1) I was following the dropbox tutorial and it says:
If the Dropbox app is installed, the SDK will switch to it so the user
doesn't have to sign in, and it will fallback to the browser if not.
If I run my app, it will open a browser with dropbox web site. Is there any way to avoid that?
2) Is it possible to download file by file name only? Can I just set url for my storage and file name without randomized url?

You can use the dropbox public folder for downloading the file that you want. You just have to put the file in that folder and then copy the url.
Then on you java you just have to put the code to download from a URL.
This is how I have done in my program and it doesn't open any browser.
A good thing about the URL in Public folder, is that it doesn't change if the filename doesn't change, so you can update your file and the URL will be the same

You can simply use client to download file by name
DbxEntry.File md;
File file = new File("destination.file");
OutputStream out = new FileOutputStream(file);
try {
md = client.getFile("/path/to/target.file", null, out);
} finally {
out.close();
}
Here null indicates that you want to receive the latest revision of file. And "/path/to/target.file" is path to file on your dropbox, like "/Public/001.jpg".
Also md can be used to retrieve some metadata about this file, like its size, name, revision, etc.

Related

Android Studio cannot read from file, does not exist

I'm trying to read from a file in Android Studio, in a small Java app. So I'm trying this:
File test = new File("C:\\testing\\testFile.dat");
if (test.exists()) {
System.out.println("test exists");
}
else {
System.out.println("test doesn't exist");
}
The file definitely exists, but it keeps on reporting that the file doesn't exist. I was able to work around this with another file by using the AssetManager and reading it through a stream, but the method I'm calling now requires a File's absolute path, but it's point blank refusing to find the file.
Am I doing something dumb, or misunderstanding something?
UPDATE
Ok, thanks for the input, I've now solved the problem. First I had to upload the file I wanted into the virtual device's storage, then I was able to get the path to it.
File test = new File(this.getFilesDir().getAbsolutePath(), "testFile.dat");
but the method I'm calling now requires a File's absolute path
Assets are files on your development machine. They are not files on the device.
Ideally, you switch to some library that supports InputStream or similar options, rather than requiring a filesystem path. If that is not an option, you can always get the InputStream from AssetManager and use that to make a copy of the data in some file that you control (e.g., in getCacheDir()). You can then pass the path to that file to this method.
You can place this file in your assets/ folder inside the android project and access using the following code.
val inputSteam = assets.open("testFile.dat")
or place it inside the res/raw folder and access it like below.
val inputStream = resources.openRawResource(R.raw.testFile)
We can't access a file on a development machine like this and won't be available on an android device so it will break so it's better if we move this somewhere inside the project and access it as above.

Storing files in project directory using Spring

I am trying to work through Spring tutorials on file uploads. What I'm trying to do is have the file be saved to a folder within the project. The folder is called "files" and is separate from the src folder.
|bin
|build
|src
|files
I have this code which accepts a file upload:
public #ResponseBody String handleFileUpload(#RequestParam("name") String name,
#RequestParam("file") MultipartFile file){
if (!file.isEmpty()) {
try {
byte[] bytes = file.getBytes();
BufferedOutputStream stream =
new BufferedOutputStream(new FileOutputStream(new File(name)));
stream.write(bytes);
stream.close();
//file.transferTo(); help?
return "You successfully uploaded " + name + "!";
What I want to do is use transferTo()to move the file to the "files" directory. When I try the true path, or try some sort of relative path I get this error which is created in the web window I am uploading files in.
Failed to upload file => "uploadedFileName/directory" does not exist
I am not sure why the file name is being appended to the directory path. Any assistance on this is much appreciated.
When you are trying to save the uploaded file to the file "uploadedFileName/directory", you are using relative file path. It's relative to the current working directory of the java process (java process, running your Tomcat Application Server or whatever appserver you are using). And that current working directory is not your project root. The following code:
System.out.println(new File(name).getAbsolutePath())
will print you the exactly path where you are trying to save your uploaded file.
To fix that issue you have to explicitly specify your project root:
File rootDir = new File("C:/Projects/myTestProject");
File uploadedFile = new File(rootDir, name);
file.transferTo(uploadedFile);
In real project you will want not to hardcode that rootDir path, but to retrieve it from some configuration file.
Don't rely to the current working directory of the application server. It could point to any directory.
PS that's out of scope of this question, but please be careful with saving data to the user-provided file names. Malicious user could post file with name "../../../../../../../../SomeSensitiveDirectory/SomeFile" and will overwrite that file unless you explicitly check that input parameter name for bad characters.
When you upload a file, you have to save it to another file.
You should use File#createTempFile() which takes a directory instead.
<p style="border-style:solid; border-color:#FFFFFF;">
<br>
File file = File.createTempFile("upload-", ".bin", new File("/path/to/your/uploads"));
<br><br>
item.write(file);
<br><br></p>

Can't find folder or file created with Android App with windows file exlorer

I'm creating a directory and a text file on the sdcard in one of my apps because I want to be able to move it to my computer for analysis. But I can't find the folder or the file I'm creating on my sdcard using the file browser on my computer.
I CAN find and read the file using my phones file manager but not using the file browser in windows.
So the file and folder are succesfully created and I can write to the file, I can also find and read the file using the file manager on my phone but I can't find either directory or file using my computer.
I have a uses permission for the application to allow it to write to external storage.
This is the code I use to create the file and directory.
String fileName = "testFil.txt";
String path = Environment.getExternalStorageDirectory().getAbsolutePath()+"/PulsApp";
File appDirectory = new File(path);
appDirectory.mkdirs();
File file = new File(path, fileName);
try {
file.createNewFile();
} catch (IOException e) {
}
Does anyone know what the problem is and how to fix it? I really need to be able to write files to my sdcard so I can transfer them to my computer.
I am completely baffled by this problem since all the research I've done point to that everyone else is doing the same thing.
If your device is running Android 3.0 or higher, you also need to use MediaScannerConnection to index your newly-created file before it will show up on a development PC's file explorer.
More accurately, the newly-created file needs to be indexed by the MediaStore. That will eventually happen for other reasons (e.g., device reboot). However, you are better served using scanFile() on MediaScannerConnection to get it to happen more quickly.
I blogged about this last summer.
Sometimes that the MediaScannerConnection will recognize the folder as a unknown type file, so try to create another folder inside the original one can avoid this problem.
I have met the same problem, and I use the method in the comment
And it works for me.

How selenium can test if it has read access to a file

Our test-app runs on multiple Virtual Machines through Selenium Remote Control.
The App sits on a test controller Server.
The test-app is used to test a third party online application.
How can I test to see if on certain VM Selenium-RC has read access to a file or folder.
Is there anything like file.canRead(filepath) kind of thing for selenium too?
Before you respond:
File's canRead(filepath) will only test if the file is readable from a test controller server, not able to say anything if it is readable on VM where actual browsers are opening(testing) third-party-online-application.
Basically, I want to upload some file to the third-party-online-application through selenium.
Before doing an upload, I want to make sure that the file is available for upload (on VMs).
A solution would be to create a download link in the application and then attempt to download the file via Selenium. That way, you get a user-representative experience.
If you want to be really fancy, have the Application create a file with the current date and then let the test download the file (simple text file) and check if the file contains the date. Then you test application writing a file and user reading the file, which covers access rights as well.
Which scripting language you are using? If assuming that your file to upload resides under "./data" directory then in java you can check with following steps
File file = new File("./data/myfile.ext");
boolean canUpload = file.exists() && file.canRead();
String fileToUpload = file.getCanonicalPath(); //file name with full path
File file = new File("Folder_Location"); // Folder path if file name not known
boolean canUpload = file.listFiles()[index].canRead();
Note : For latest downloaded file use
int size=file.listFiles().length-1;
boolean canUpload = file.listFiles()[size].canRead();

java- jar file cannot find resources

I 'm working on a java application and in the program I use some files such as images, a local database and an .htm file (used as help file).
I have tried to make the access to these resources, location independent. So I've made in the package that contains my source files, a subfolder named resources and I've put there all these images,etc. I access them through .getResource() method, and not by using paths. For example that's how i access an image resource:
lang_icon=new javax.swing.ImageIcon(getClass().getResource("/myeditor/resources/checked.gif"));
The problem is that when the .jar file is built, it doesn't work properly. It loads the images successfully but cannot connect to the local database or open the .htm file.
Here is the code I use to access the .htm file (it works fine when I run the application through Netbeans)
URL helpFile= getClass().getResource("/myeditor/resources/help/help.htm");
try {
BrowserLauncher launcher = new BrowserLauncher();
launcher.openURLinBrowser(helpFile.toString());
} catch (BrowserLaunchingInitializingException ex) {
Logger.getLogger(mainAppFrame.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnsupportedOperatingSystemException ex) {
Logger.getLogger(mainAppFrame.class.getName()).log(Level.SEVERE, null, ex);
}
and here is the code I use to access my local database
URL url = getClass().getResource("/myeditor/resources/icddb");
database = new File(url.getFile());
try
{
Class.forName("org.hsqldb.jdbcDriver");
con = DriverManager.getConnection("jdbc:hsqldb:file:" + database+"\\icddb", "sa", "");
When I try to open the .htm file through .jar file it shows this error "This file does not have a program associated with it for performing this action. Create an association in the Folder Options in control panel".
When I try to connect to my local database it says "Severe could not reopen database".
All ideas appreciated!
Thank you and sorry for my english!
Can you print out the URL you're asking the browser to open ? That should give a clearer indication as to what's going on.
I suspect the URL you're getting from getResource() is a URL pointing to within your .jar file. As such the browser is going to have difficulty opening that. I would (perhaps) extract that file to a temporary directory and have the browser open that.

Categories