I'm writing this post because I need some help.
I'm having trouble display an image depending on a specific path in my App.
Basically what it's doing: I have a module named Sector, and each Sector can have an image related to it. When I use the Upload component of Vaadin, I save the path of the image to a table in my database so that it can display the picture chosen before.
The actual path of the image is weird, it seems that Vaadin copies the image to a dynamic random folder. It seems logical that it can't use the actual path of the image.
But here's the problem: The path is well entered in the Database, but when I reload the page (F5), Vaadin can't shows the image anymore. Which upsets me since it should display it well.
The path that Vaadin creates with the uploaded image : VAADIN/dynamic/resource/2/c1ef7b9d-8f2b-4354-a97e-fe1fd4e868e7/551434.jpg
I can put some code if it can help.
The screenshots show what it's doing once I'm refreshing the browser page.
The image is being uploaded
After refreshing the page
Here is the part of the code where I handle the upload image:
upload.addSucceededListener(e -> {
Component component = createComponent(e.getMIMEType(),
e.getFileName(), buffer.getInputStream());
showOutput(e.getFileName(), component, output);
//imgUpload = (Image) component;
InputStream inputStream = buffer.getInputStream();
targetFile = new File(PATH + currentProjetId + "\\secteur" + currentSecId + "\\photoSec.png");
try {
FileUtils.copyInputStreamToFile(inputStream, targetFile);
} catch (IOException e1) {
e1.printStackTrace();
Notification.show("Error");
}
System.out.println("PATH : " + targetFile.getPath());
});
I think you are using an in-memory resource that's discarded when you refresh the view. You have to take the contents of the file and save it in a file inside a directory in the server's file system. Here's an example:
FileBuffer receiver = new FileBuffer();
Upload upload = new Upload(receiver);
upload.setAcceptedFileTypes("text/plain");
upload.addSucceededListener(event -> {
try {
InputStream in = receiver.getInputStream();
File tempFile = receiver.getFileData().getFile();
File destFile = new File("/some/directory/" + event.getFileName());
FileUtils.moveFile(tempFile, destFile);
} catch (IOException e) {
e.printStackTrace();
Notification.show("Error").
}
});
Related
I have Successfully created folder and uploaded file in Document and Media Library.
I am storing File Name in DB and based on that file name I want to fetch that specific file from Document Library. I am new to Liferay.
I am fetching all Files saved in Document & Media Library using this Code Snippet. But is there any way to directly fetch File using File Name.
Here is my Code Snippet
public void getAllDLFileLink(ThemeDisplay themeDisplay,String folderName){
try {
Folder folder =DLAppServiceUtil.getFolder(themeDisplay.getScopeGroupId(), DLFolderConstants.DEFAULT_PARENT_FOLDER_ID, folderName);
List<DLFileEntry> dlFileEntries = DLFileEntryLocalServiceUtil.getFileEntries(themeDisplay.getScopeGroupId(), folder.getFolderId());
for (DLFileEntry file : dlFileEntries) {
String url = themeDisplay.getPortalURL() + themeDisplay.getPathContext() + "/documents/" + themeDisplay.getScopeGroupId() + "/" +
file.getFolderId() + "/" +file.getTitle() ;
System.out.println("DL Link=>"+url);
}
} catch (Exception e) {
e.printStackTrace();
}
}
As your code snippet already finds the URL for a DLFileEntry, I'm assuming that you want to get hold of the binary content. Check DLFileEntry.getContentStream().
If this assumption is wrong and you want to embed the image in the HTML output of your portlet, use the URL within an <img src="URL-HERE"/> tag
You can use DLFileEntryLocalServiceUtil.getFileEntry(long groupId, long folderId, java.lang.String title) to get file using file name / title, as following:
String fileName = "abc.jpg";
Folder folder = DLAppServiceUtil.getFolder(themeDisplay.getScopeGroupId(),
DLFolderConstants.DEFAULT_PARENT_FOLDER_ID, folderName);
DLFileEntry dlFileEntry = DLFileEntryLocalServiceUtil.getFileEntry(
themeDisplay.getScopeGroupId(), folder.getFolderId(), fileName);
However, title is stored with extension, therefore, you will require to pass complete name of image / file.
In my application I have several images in drawable folder. That makes apk big. Now I have uploaded them in my Google drive and when the user will connect to the internet it will download that images from drive. Where to save that downloaded images? in external storage , in database or in other place? I want that the user couldn't delete that images.
You can store them in Internal phone memory.
To save the images
private String saveToInternalSorage(Bitmap bitmapImage){
ContextWrapper cw = new ContextWrapper(getApplicationContext());
// path to /data/data/yourapp/app_data/imageDir
File directory = cw.getDir("youDirName", Context.MODE_PRIVATE);
// Create imageDir
File mypath=new File(directory,"img.jpg");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(mypath);
// Use the compress method on the BitMap object to write image to the OutputStream
bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
return directory.getAbsolutePath();
}
To access the stored file
private void loadImageFromStorage(String path)
{
try {
File f = new File(path, "img.jpg");
Bitmap b = BitmapFactory.decodeStream(new FileInputStream(f));
// here is the retrieved image in b
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
EDIT
You can save files directly on the device's internal storage. By default, files saved to the internal storage are private to your application and other applications cannot access them (nor can the user). When the user uninstalls your application, these files are removed.
For more information Internal Storage
I want that the user couldn't delete that images
You can't really do that. Images weren't here unless user selected them so why you do not want to let user delete them? in such case you will download it again or ask user to select. normal "cache" scenario. Not to mention you are in fact unable to protect these images as user can always clear app data (including databases and internal storage).
BACKGROUND
Hey so I have a camera that I have implemented myself in code. This means I access and control the camera hardware and use it to save pictures. I can save the picture using the Camera.takePicture() function when the camera is running: running means Camera.startPreview();
PROBLEM
My problem is that I want to be able to save the image also when the camera image is frozen: frozen is when Camera.stopPreview(); is called.When frozen I can see the image in my layout but how do I access it? Where is the image saved so that I might be able to modify it later?
Thanks in advance!
------------------Update 1
jpeg bla;
public class jpeg implements PictureCallback{
public void onPictureTaken(byte[] data, Camera camera) {
g_data = data;
}
}
This is part of my code. Here I am trying to write the data that would originally be saved to a global variable. However the value of g_data remains null and I am unable to set a breakpoint inside the onPictureTaken() call back function.
------------------Update 2
FileOutputStream outStream = null;
try {
// generate the folder
File imagesFolder = new File(Environment.getExternalStorageDirectory(), "MirrorMirror");
if( !imagesFolder.exists() ) {
imagesFolder.mkdirs();
}
// generate new image name
SimpleDateFormat formatter = new SimpleDateFormat("HH_mm_ss");
Date now = new Date();
String fileName = "image_" + formatter.format(now) + ".jpg";
// create outstream and write data
File image = new File(imagesFolder, fileName);
outStream = new FileOutputStream(image);
outStream.write(data);
outStream.close();
Log.d(TAG, "onPictureTaken - wrote bytes: " + data.length);
} catch (FileNotFoundException e) { // <10>
//Toast.makeText(ctx, "Exception #2", Toast.LENGTH_LONG).show();
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {}
I used this code previously to save the file from the camera onPictureTaken() function. The key here is the byte[] data which I need to save and save later. However like I said I just get a null when I check it in the debugger.
Camera.takePicture never looks at the view you specified as previewDisplay. Actually, it isn't an ImageView, but a SurfaceView, and there are no API to read pixels from it.
You can call takePicture() preemptively just before you stopPreview(). Later, if you find out that you don't need the picture, just discard it.
Ok so the exact way to do this is to take the picture just before stopPreview() and save it to a temporary file. Actually with this implementation you never call stopPreview()(otherwise it will crash) since the takePicture() function stops the preview automatically.
try {
File temp = File.createTempFile("temp", ".jpg");
} catch (IOException e) {
e.printStackTrace();
}
Now that we have the temporary file saved we will access it later and move it to our new desired file location.
How to copy file.
temp.deleteOnExit();
be sure to call deleteonExit() so that Android deletes the file after the app is closed(if so desired).
I'm new here and kinda new to java.
I've encountered a problem.
I have a very simple program that tries to create pngs and save them in a user selected folder.
byteimage is a a private byte[]:
byteimage = bcd.createPNG(300, 140, ColorSpace.TYPE_RGB, Color.BLACK, Color.BLACK);
setPath() is called inside the action listener of the browse button
private void setPath() {
JFileChooser pathchooser = new JFileChooser();
pathchooser.setMultiSelectionEnabled(false);
pathchooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
pathchooser.setApproveButtonMnemonic(KeyEvent.VK_ENTER);
pathchooser.showDialog(this, "OK");
File f = pathchooser.getSelectedFile();
if (f != null) {
filepath = f.getAbsolutePath();
pathfield.setText(filepath);
}
}
Byte to png method looks like this:
public void byteToPNG(String filename) {
try {
InputStream in = new ByteArrayInputStream(byteimage);
BufferedImage bufferedimg = ImageIO.read(in);
ImageIO.write(bufferedimg, "png", new File(filename));
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
This method is called like this:
byteToPNG(pathfield.getText() + System.getProperty("file.separator") + textfield.getText() + ".png");
textfield.getText() sets the actual name of the png.
Inside the constructor, default filepath is set:
filepath = System.getProperty("user.dir");
pathfield.setText(filepath);
The code runs fine from Eclipse and it produces a png image at the desired location.
Unfortunately, after exporting as jar, it starts but when the button for generating the png is pressed, nothing happens. I'm thinking there's a problem at InputStream or BufferedImage, but I'm a bit puzzled.
If the String fileName passed to byteToPNG isn't absolute (i.e. written in the form "C:/foo/bar/etc") that could be the cause of the broken jar. You could also try running the jar file in the terminal using the command:
java -jar myJarFile.jar.
This will cause a console window to remain open alongside your running jar application in which all your applications output (including any exceptions) will be printed.
This question already has answers here:
Recommended way to save uploaded files in a servlet application
(2 answers)
Closed 6 years ago.
Hello once again i ask question on stackOverflow :D
how can i upload file with JSF using primefaces?
i have method handle Upload Image
public void handleFileUpload(FileUploadEvent event) {
ExternalContext extContext = FacesContext.getCurrentInstance().
getExternalContext();
File result = new File(extContext.getRealPath
("//admin//item") + "//" + event.getFile().getFileName());
try {
FileOutputStream fileOutputStream = new FileOutputStream(result);
byte[] buffer = new byte[BUFFER_SIZE];
int bulk;
InputStream inputStream = event.getFile().getInputstream();
while (true) {
bulk = inputStream.read(buffer);
if (bulk < 0) {
break;
}
fileOutputStream.write(buffer, 0, bulk);
fileOutputStream.flush();
}
fileOutputStream.close();
inputStream.close();
FacesMessage msg = new FacesMessage("Succesful",
event.getFile().getFileName() + " is uploaded.");
FacesContext.getCurrentInstance().addMessage(null, msg);
} catch (IOException e) {
e.printStackTrace();
FacesMessage error = new FacesMessage("The files were not uploaded!");
FacesContext.getCurrentInstance().addMessage(null, error);
}
}
it work well but it just work when server deploy, when i upload image to server , folder //admin/item/ have image but when i re-start server i can't find image i was uploaded
and how can i display thumbnails for each item with each own image
but when i re-start server i can't find image i was uploaded
That's normal in most servletcontainer configurations. When you restart the server or redeploy the webapp, any previously expanded webapp files will be deleted and the WAR will be re-expanded. You shouldn't store uploaded files in the expanded folder for the case you'd like to keep them longer than the webapp context lives.
The normal practice is to store them in a fixed path outside the webapp context, e.g. /var/webapp/upload.
File file = new File("/var/webapp/upload", event.getFile().getFileName());
Unrelated to the problem, I'd suggest to make use of File#createTempFile() to avoid that another uploaded file which has -by coincidence- the same filename will overwrite any previously uploaded one.