Jar executable of spring app file upload failed? - java

This spring app performs simple file upload,
here's the controller class
#Override
public String fileUpload(MultipartFile file) {
try{
// save uploaded image to images folder in root dir
Files.write(Paths.get("images/"+ file.getOriginalFilename()), file.getBytes());
// perform some tasks on image
return "";
} catch (IOException ioException) {
return "File upload has failed.";
} finally {
Files.delete(Paths.get("images/" + file.getOriginalFilename()));
}
}
but when i build jar and runs, it throws IOException saying,
java.nio.file.NoSuchFileException: images\8c9.jpeg.
So my question is how can i add the images folder inside the jar executable itself.
Thanks.

You should provide a full path for the images folder, or save in java.io.tmpdir creating the image folder first.
But, in my opinion you should configure your upload folder from a config file for flexibility. Take a look at this.
app:
profile-image:
upload-dir: C:\\projs\\web\\profile_image
file-types: jpg, JPG, png, PNG
width-height: 360, 360
max-size: 5242880
In your service or controller, do whatever you like, may be validate image type, size etc and process it as you like. For instance, if you want thumbnails(or avatar..).
In your controller or service class, get the directory:
#Value("${app.image-upload-dir:../images}")
private String imageUploadDir;
Finally,
public static Path uploadFileToPath(String fullFileName, String uploadDir, byte[] filecontent) throws IOException {
Path fileOut = null;
try{
Path fileAbsolutePath = Paths.get(StringUtils.join(uploadDir, File.separatorChar, fullFileName));
fileOut = Files.write(fileAbsolutePath, filecontent);
}catch (Exception e) {
throw e;
}
return fileOut; //full path of the file
}
For your question in the comment: You can use java.io.File.deleteOnExit() method, which deletes the file or directory defined by the abstract path name when the virtual machine terminates. TAKE A GOOD CARE THOUGH, it might leave some files if not handled properly.
try (ByteArrayOutputStream output = new ByteArrayOutputStream();){
URL fileUrl = new URL(url);
String tempDir = System.getProperty("java.io.tmpdir");
String path = tempDir + new Date().getTime() + ".jpg"; // note file extension
java.io.File file = new java.io.File(path);
file.deleteOnExit();
inputStream = fileUrl.openStream();
ByteStreams.copy(inputStream, output); // ByteStreams - Guava
outputStream = new FileOutputStream(file);
output.writeTo(outputStream);
outputStream.flush();
return file;
} catch (Exception e) {
throw e;
} finally {
try {
if(inputStream != null) {
inputStream.close();
}
if(outputStream != null) {
outputStream.close();
}
} catch(Exception e){
//skip
}
}

Related

why can't I use getExternalStoragePublicDirectory() to create a folder on my SD card and store photos in it?

I got a FileNotFoundException#5818 when I try to get a file address using getExternalStoragePublicDirectory().
This is my method copied from Google Dev Documentation:
public File getPublicDir(String albumName) {
// Get the directory for the user's public pictures directory.
File file = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), albumName);
if (!file.mkdirs()) {
Log.e("PUBLIC DIRECTORY", "Directory not created");
}
return file;
}
I call this method here:
try{
FileOutputStream fos=new FileOutputStream(getPublicDir("mySnapshot"));
Boolean success=snapshot.compress(Bitmap.CompressFormat.PNG, 100, fos);
Toast.makeText(MainActivity.this,"Compress?
:"+success,Toast.LENGTH_SHORT).show();
fos.close();
}catch(IOException e){
e.printStackTrace();
Toast.makeText(MainActivity.this,"NOT SAVED",Toast.LENGTH_SHORT).show();
}
I am not exactly sure what albumName is. Is it the name of the folder to be created or the name of the photo file to be stored?
Here is a screenshot of the error it throws when I was debugging:
It throws the error at line "FileOutputStream fos=new FileOutputStream(getPublicDir("mySnapshot"));."
Write permission added.
Here is what my app looks like (GIF), and the error it throws:
This is where I create a folder (GIF):\
I found here a way to write text into directory, it works but it's only for text:
try {
FileOutputStream fos = new FileOutputStream(myExternalFile);
fos.write(inputText.getText().toString().getBytes());
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
myExternalFile = new File(getExternalFilesDir(filepath), filename);
private String filename = "SampleFile.txt";
private String filepath = "MyFileStorage";

Downloading files from a server and put it to /raw folder

Here is I want to make. I want to make an app, for example it has a button that will download a certain video file and put it on the resource(raw) folder. Is it possible?
Short answer : You can not.
You can not, under any circumstance, write/dump a file to the raw/assets folder in runtime.
What you can do is to download the video and store it into Internal Memory (application reserved storage) or External Memory (usually your SDCard))
For example, you can store media files, for instance a Bitmap to your external storage like this.
private void saveAnImageToExternalMemory(Bitmap finalBitmap) {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/saved_images");
myDir.mkdirs();
String fname = "yourimagename.jpg";
File file = new File (myDir, fname);
if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
And equally, read an file, in this example an image (which is then loaded to an imageView), from external memory
private void loadImageFromStorage(String path){
try {
File f=new File(path, "profile.jpg");
Bitmap b = BitmapFactory.decodeStream(new FileInputStream(f));
ImageView img=(ImageView)findViewById(R.id.imgPicker);
img.setImageBitmap(b);
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
Edit: Additionally, you can store your data into internal memory
Alternatively you can also save the Bitmap to the internal storage in
case the SD card is not available or for whatever other reasons you
may have. Files saved to the internal storage are only accessible by
the application which saved the files. Neither the user nor other
applications can access those files
public boolean saveImageToInternalStorage(Bitmap image) {
try {
FileOutputStream fos = context.openFileOutput("yourimage.png", Context.MODE_PRIVATE);
// Writing the bitmap to the output stream
image.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
return true;
} catch (Exception e) {
Log.e("saveToInternalStorage()", e.getMessage());
return false;
}
}
Check this documentation for more information
Regards,

How to access /data folder of another application through your application?

there is a text file that an application produces, I would like to take that file and read it as strings in my application. How can I achieve that, any help would be grateful. Both applications are my applications so I can get the permissions.
Thank you!
This is possible using the standard android-storage, where all the user's files are stored too:
All you need to do is to access the same file and the same path in both applications, so e.g.:
String fileName = Environment.getExternalStorageDirectory().getPath() + "myFolderForBothApplications/myFileNameForBothApplications.txt";
Where myFolderForBothApplications and myFileNameForBothApplications can be replaced by your folder/filename, but this needs to be the same name in both applications.
Environment.getExternalStorageDirectory() returns a File-Object to the common, usable file-directory of the device, the same folder the user can see too.
By calling the getPath() method, a String representing the path to this storage is returned, so you can add your folder/filenames afterwards.
So a full code example would be:
String path = Environment.getExternalStorageDirectory().getPath() + "myFolderForBothApplications/";
String pathWithFile = path + "myFileNameForBothApplications.txt";
File dir = new File(path);
if(!dir.exists()) { //If the directory is not created yet
if(!dir.mkdirs()) { //try to create the directories to the given path, the method returns false if the directories could not be created
//Make some error-output here
return;
}
}
File file = new File(pathWithFile);
try {
f.createNewFile();
} catch (IOException e) {
e.printStackTrace();
//File couldn't be created
return;
}
Afterwards, you can write in the file or read from the file as provided e.g. in this answer.
Note that the file stored like this is visible for the user and my be edited / deleted by the user.
Also note what the JavaDoc for the getExternalStorageDirectory() says:
Return the primary external storage directory. This directory may not currently be accessible if it has been mounted by the user on their computer, has been removed from the device, or some other problem has happened. You can determine its current state with getExternalStorageState().
I do not know if this is the best/safest way to fix your problem, but it should work.
You can save the text file from your assets folder to anywhere in the sdcard, then you can read the file from the other application.
This method uses the getExternalFilesDir, that returns the absolute path to the directory on the primary shared/external storage device where the application can place persistent files it owns. These files are internal to the applications, and not typically visible to the user as media.
private void copyAssets() {
AssetManager assetManager = getAssets();
String[] files = null;
try {
files = assetManager.list("");
} catch (IOException e) {
Log.e("tag", "Failed to get asset file list.", e);
}
if (files != null) for (String filename : files) {
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(filename);
File outFile = new File(Environment.getExternalStorageDirectory(), filename);
out = new FileOutputStream(outFile);
copyFile(in, out);
} catch(IOException e) {
Log.e("tag", "Failed to copy asset file: " + filename, e);
}
finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
// NOOP
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
// NOOP
}
}
}
}
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1){
out.write(buffer, 0, read);
}
}
And to read:
File dir = Environment.getExternalStorageDirectory();
File yourFile = new File(dir, "path/to/the/file/inside/the/sdcard.ext");

Downloading files(.zip, .jar,...) to a folder

I have been trying many ways of downloading a file from a URL and putting it in a folder.
public static void saveFile(String fileName,String fileUrl) throws MalformedURLException, IOException {
FileUtils.copyURLToFile(new URL(fileUrl), new File(fileName));
}
boolean success = (new File("File")).mkdirs();
if (!success) {
Status.setText("Failed");
}
try {
saveFile("DownloadedFileName", "ADirectDownloadLinkForAFile");
} catch (MalformedURLException ex) {
Status.setText("MalformedURLException");
Logger.getLogger(DownloadFile.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Status.setText("IOException Error");
Logger.getLogger(DownloadFile.class.getName()).log(Level.SEVERE, null, ex);
}
I found this code on the net, am i using it correctly?
If i did:
saveFile("FolderName", "ADirectDownloadLinkForAFile")
I would get IOException error
What I want my code to do is:
Create folder
Download file
Downloaded file to go to the just created folder
I'm a newbie here sorry. Please help
There are various ways in java to download a file from the internet.
The easiest one is to use a buffer and a stream:
File theDir = new File("new folder");
// if the directory does not exist, create it
if (!theDir.exists())
{
System.out.println("creating directory: " + directoryName);
boolean result = theDir.mkdir();
if(result){
System.out.println("DIR created");
}
}
FileOutputStream out = new FileOutputStream(new File(theDir.getAbsolutePath() +"filename"));
BufferedInputStream in = new BufferedInputStream(new URL("URLtoYourFIle").openStream());
byte data[] = new byte[1024];
int count;
while((count = in.read(data,0,1024)) != -1)
{
out.write(data, 0, count);
}
Just the basic concept. Dont forget the close the streams ;)
The File.mkdirs() statement appears to be creating a folder called Files, but the saveFile() method doesn't appear to be using this, and simply saving the file in the current directory.

Saving file as a different name

I have a Java form in which you can select a file to open. I have that file:
File my_file = ...
I want to be able to save my file as a different name.
how can I do it using "File my_file"?
I tried:
File current_file = JPanel_VisualizationLogTab.get_File();
String current_file_name = current_file.getName();
//String current_file_extension = current_file_name.substring(current_file_name.lastIndexOf('.'), current_file_name.length()).toLowerCase();
FileDialog fileDialog = new FileDialog(new Frame(), "Save", FileDialog.SAVE);
fileDialog.setFile(current_file_name);
fileDialog.setVisible(true);
But that doesn't save the file.
I would recommend using the Apache Commons IO library to make this task easier. With this library, you could use the handy FileUtils class that provides many helper functions for handling file IO. I think you would be interested in the copy(File file, File file) function
try{
File current_file = JPanel_VisualizationLogTab.get_File();
File newFile = new File("new_file.txt");
FileUtils.copyFile(current_file, newFile);
} catch (IOException e){
e.printStackTrace();
}
Documentation
If you want to copy it with a different name, i found this piece of Code via google
public static void copyFile(File in, File out) throws IOException {
FileChannel inChannel = new FileInputStream(in).getChannel();
FileChannel outChannel = new FileOutputStream(out).getChannel();
try {
inChannel.transferTo(0, inChannel.size(), outChannel);
} catch (IOException e) {
throw e;
} finally {
if (inChannel != null)
inChannel.close();
if (outChannel != null)
outChannel.close();
}
}
now you can call it with
File inF = new File("/home/user/inputFile.txt");
File outF = new File("/home/user/outputFile.txt");
copyFile(inF, outF);
it´s just important that both Files exist, otherswise it will raise an exception
You can rename the file name.
Use:
myfile.renameTo("neeFile")
There is a Method called renameTo(new File("whatever you want")); for File Objects

Categories

Resources