Load DLL library in my Applet - java

When I try to run my applet on the server, it never seems to go out the first step, that is, loading libraries, and when I try to run on localhost, works perfectly
CODE
private final static String DEFAULT_DOWNLOAD_PATH = "http://colorfulwolf.com/dev/cam/";
private final static String VERSION_ID = "1.0.0";
// note that this list is windows-specific, so this is not a generic
// solution that works on all OSes
private final static String[] LIBS = { "cv210.dll", "cvaux210.dll",
"cxcore210.dll", "cxts210.dll", "highgui210.dll", "ml210.dll" };
private final static String LIB_ARCHIVE = "opencv21.zip";
public void loadWebcam() {
loadingScreen.setMaxProgress(7);
loadingScreen.setProgress(1, "Loading Librarys..");
String tmpDir = System.getProperty("java.io.tmpdir");
File faPath = new File(tmpDir + File.separator + "WebcamApplet_"
+ VERSION_ID.replaceAll("\\.", "-"));
System.out.println(faPath);
System.setProperty("jna.library.path", faPath.getAbsolutePath());
String downloadPath = this.getParameter("dll_path");
if (downloadPath == null)
downloadPath = DEFAULT_DOWNLOAD_PATH;
try {
prepareLibraries(faPath, downloadPath);
} catch (Exception e) {
e.printStackTrace();
loadingScreen.setProgress(3, "Erro: " + e.getMessage());
return;
}
}
private void prepareLibraries(File localPath, String downloadPath)
throws Exception {
if (localPath.exists()) {
boolean libMissing = false;
for (String lib : LIBS) {
File libFile = new File(localPath.getAbsolutePath()
+ File.separator + lib);
if (!libFile.exists()) {
libMissing = true;
break;
}
}
if (!libMissing)
return; // We don't have to download
}
if (!localPath.exists() && !localPath.mkdirs()) // Error fatal!
throw new Exception("Can't create the path: " + localPath);
loadingScreen.setProgress(2, "Downloading library...");
File file = new File(localPath.getAbsolutePath() + File.separator
+ LIB_ARCHIVE);
String link = downloadPath + LIB_ARCHIVE;
download(link, file);
ZipFile zipFile = new ZipFile(file);
Enumeration<? extends ZipEntry> entries = zipFile.entries();
loadingScreen.setProgress(3, "Installing librarys..");
while (entries.hasMoreElements()) {
ZipEntry entry = entries.nextElement();
if (entry.isDirectory())
continue;
File tar = new File(localPath.getAbsolutePath() + File.separator
+ entry.getName());
InputStream is = zipFile.getInputStream(entry);
OutputStream os = new FileOutputStream(tar);
copyStream(is, os);
os.flush();
os.close();
is.close();
}
zipFile.close();
file.delete();
if (file.exists())
file.deleteOnExit();
}
I put the jar files on the server in a visible HTTP path
<applet code="com.colorfulwolf.webcamapplet.WebcamApplet"
archive="http://www.netimoveis.com/teste.jar, http://www.netimoveis.com/core.jar, http://www.netimoveis.com/javacv.jar, http://www.netimoveis.com/javase.jar, http://www.netimoveis.com/jna.jar, http://www.netimoveis.com/customizer.jar, http://www.netimoveis.com/jmf.jar, http://www.netimoveis.com/meidaplayer.jar, http://www.netimoveis.com/multiplayer.jar, http://www.netimoveis.com/sound.jar"
height="550" width="550">
</applet>
Why when I try to run the applet on the server, it does not leave the first step?
#UPDATE
I found the line where the code don't move to the next line of code.
String tmpDir = System.getProperty("java.io.tmpdir"); this line is where my code stop and still just in this line. Java is currently installed in server.

Related

Variable path for file storage based on a user's group

I am working on an application that allows users to upload files. I want to keep the uploaded files organized into pre-created folders named for the group that the user belongs to. I can't seem to find a way to make the path editable so that I can pass the group's name into the method as a parameter and have the file stored in that directory.
Here's my latest attempt that results in a "Failed to store file file] with root cause" exception.
#Service
public class StorageServiceImpl implements StorageService {
#Value("${upload.path}")
private Path path;
public void uploadFile(MultipartFile file,String contentName, String groupName){
//make so that files are stored in path/groupname
this.path = Paths.get(this.path.toString() +"/"+groupName +"/");
String filename = contentName+"-"+StringUtils.cleanPath(file.getOriginalFilename());
System.out.println("\n\n\n\n\n"+filename + "\n\n\n");
try {
if (file.isEmpty()) {
throw new StorageException("Failed to store empty file");
}
if (filename.contains("..")) {
// This is a security check
throw new StorageException(
"Cannot store file with relative path outside current directory "
+ filename);
}
try (InputStream inputStream = file.getInputStream()) {
System.out.println("\n\n\n\n\n"+this.path.resolve(filename) + "\n\n\n");
Files.copy(inputStream, this.path.resolve(filename), StandardCopyOption.REPLACE_EXISTING);
}
}catch (IOException e) {
String msg = String.format("Failed to store file %s", file.getName());
throw new StorageException(msg, e);
}
}
}
Note: If the directory of the groupName is created before this method runs (as I intend to have it created when the group is created) then the method attempts to store the file in another directory of the same name inside that directory such as:
backend/src/main/webapp/WEB-INF/TestGroup/TestGroup/test.jpg
See how TestGroup shows up twice
Instead of doing this, here you are trying to inject value to a varible of type Path.
#Value("${upload.path}")
private Path path;
how about reading the value to a String variable and storing it as a File and then using it to upload like below,
#Value("${upload.path}")
private String path;
And then using it
public void uploadFile( MultipartFile file, String contentName, String groupName )
{
String filename = contentName + "-" + StringUtils.cleanPath( file.getOriginalFilename() );
// use a File object here
File uploadFilePath = Paths.get( new File( path ).getPath() + "/" + groupName + "/" + filename ).toFile();
try
{
try( InputStream in = file.getInputStream(); OutputStream out = new FileOutputStream( uploadFilePath ) )
{
// Leverage the support of Spring's FileCopyUtils Here
FileCopyUtils.copy( in, out );
}
catch( IOException ex )
{
throw new RuntimeException( ex );
}
}
catch( IOException e )
{
String msg = String.format( "Failed to store file %s", file.getName() );
throw new StorageException( msg, e );
}
}
I got it working by using the absolutePath method from the private Path path to generate the string.
public void uploadFile(MultipartFile file,String contentName, String groupName){
//make so that files are stored in path/groupname
String filename = contentName+"-"+StringUtils.cleanPath(file.getOriginalFilename());
File uploadFilePath = Paths.get(this.path.toAbsolutePath() + "/" + groupName+"/" + filename).toFile();
try {
if (file.isEmpty()) {
throw new StorageException("Failed to store empty file");
}
if (filename.contains("..")) {
// This is a security check
throw new StorageException(
"Cannot store file with relative path outside current directory "
+ filename);
}
try (InputStream inputStream = file.getInputStream();OutputStream out = new FileOutputStream(uploadFilePath);) {
FileCopyUtils.copy(inputStream,out);
}
}catch (IOException e) {
String msg = String.format("Failed to store file %s", file.getName());
throw new StorageException(msg, e);
}
}

Building ZIP files on Android

I am using the following code to build a zip file on my external storage, the only problem is that the file can't be extracted on a Windows PC or be used for anything other than Android, I think I have narrowed the problem to a non-existent folder.
My question is what have I done wrong to cause a weird format of zip?
/**
EXAMPLE USAGE : zipFolder("/sdcard0/downloads", "/sdcard0/Update.zip")
**/
static public void zipFolder(String srcFolder, String destZipFile)
throws Exception
{
ZipOutputStream zip = null;
FileOutputStream fileWriter = null;
fileWriter = new FileOutputStream(destZipFile);
zip = new ZipOutputStream(fileWriter);
addFolderToZip("", srcFolder, zip);
zip.flush();
zip.close();
}
static String firstFolder ="";
static private void addFileToZip(String path, String srcFile,
ZipOutputStream zip) throws Exception
{
if (firstFolder == "")
{
firstFolder = getLastPathComponent(path);
}
File folder = new File(srcFile);
if (folder.isDirectory())
{
addFolderToZip(path, srcFile, zip);
}
else
{
byte[] buf = new byte[1024];
int len;
FileInputStream in = new FileInputStream(srcFile);
zip.putNextEntry(new ZipEntry(path.replace(firstFolder, "") + "/" + folder.getName()));
while ((len = in.read(buf)) > 0)
{
zip.write(buf, 0, len);
}
}
}
public static String getLastPathComponent(String filePath)
{
String[] segments = filePath.split("/");
if (segments.length == 0)
return "";
String lastPathComponent = segments[segments.length - 1];
return lastPathComponent;
}
static private void addFolderToZip(String path, String srcFolder,
ZipOutputStream zip) throws Exception
{
File folder = new File(srcFolder);
for (String fileName : folder.list())
{
if (path.equals(""))
{
addFileToZip(folder.getName().replace(firstFolder, ""), srcFolder + "/" + fileName, zip);
}
else
{
addFileToZip(path + "/" + folder.getName(), srcFolder + "/"
+ fileName, zip);
}
}
}

How to copy resources folder out of jar into program files

I have spent hours and hours searching for the answer and I just can't figure it out, I am trying to copy my resources folder which contains all the images and data files for my game I am working on out of the running jar and into
E:/Program Files/mtd/ It works fine when I run it out of eclipse, but when I export the jar and try it, I get NoSuchFileException
`JAR
Installing...
file:///C:/Users/Cam/Desktop/mtd.jar/resources to file:///E:/Program%20Files/mtd
/resources
java.nio.file.NoSuchFileException: C:\Users\Cam\Desktop\mtd.jar\resources
at sun.nio.fs.WindowsException.translateToIOException(Unknown Source)
at sun.nio.fs.WindowsException.rethrowAsIOException(Unknown Source)
at sun.nio.fs.WindowsException.rethrowAsIOException(Unknown Source)
at sun.nio.fs.WindowsFileAttributeViews$Basic.readAttributes(Unknown Sou
rce)
at sun.nio.fs.WindowsFileAttributeViews$Basic.readAttributes(Unknown Sou
rce)
at sun.nio.fs.WindowsFileSystemProvider.readAttributes(Unknown Source)
at java.nio.file.Files.readAttributes(Unknown Source)
at java.nio.file.FileTreeWalker.walk(Unknown Source)
at java.nio.file.FileTreeWalker.walk(Unknown Source)
at java.nio.file.Files.walkFileTree(Unknown Source)
at java.nio.file.Files.walkFileTree(Unknown Source)
at me.Zacx.mtd.main.Game.<init>(Game.java:94)
at me.Zacx.mtd.main.Game.main(Game.java:301)`
This is the code I am using:
if (!pfFolder.exists()) {
pfFolder.mkdir();
try {
URL url = getClass().getResource("/resources/");
URI uri = null;
if (url.getProtocol().equals("jar")) {
System.out.println("JAR");
JarURLConnection connect = (JarURLConnection) url.openConnection();
uri = new URI(connect.getJarFileURL().toURI().toString() + "/resources/");
} else if (url.getProtocol().equals("file")) {
System.out.println("FILE");
uri = url.toURI();
}
final Path src = Paths.get(uri);
final Path tar = Paths.get(System.getenv("ProgramFiles") + "/mtd/resources/");
System.out.println("Installing...");
System.out.println(src.toUri() + " to " + tar.toUri());
Files.walkFileTree(src, new SimpleFileVisitor<Path>() {
public FileVisitResult visitFile( Path file, BasicFileAttributes attrs ) throws IOException {
return copy(file);
}
public FileVisitResult preVisitDirectory( Path dir, BasicFileAttributes attrs ) throws IOException {
return copy(dir);
}
private FileVisitResult copy( Path fileOrDir ) throws IOException {
System.out.println("Copying " + fileOrDir.toUri() + " to " + tar.resolve( src.relativize( fileOrDir ) ).toUri());
Files.copy( fileOrDir, tar.resolve( src.relativize( fileOrDir ) ) );
return FileVisitResult.CONTINUE;
}
});
System.out.println("Done!");
} catch (IOException e) {
e.printStackTrace();
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
This was harder that I thought, but here is how to do it.
here is my copy method Reference https://examples.javacodegeeks.com/core-java/io/file/4-ways-to-copy-file-in-java/
public void copyFile(String inputPath, String outputPath ) throws IOException
{
InputStream inputStream = null;
OutputStream outputStream = null;
try {
inputStream = getClass().getResourceAsStream(inputPath);
outputStream = new FileOutputStream(outputPath);
byte[] buf = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buf)) > 0) {
outputStream.write(buf, 0, bytesRead);
}
}
finally {
inputStream.close();
outputStream.close();
}
Please note the structure of the project of the Jar file in this image Project structure
Now I need to read the Jar file. This is a varition on this solution How can I get a resource "Folder" from inside my jar File? . Both of these methods work together to product the result. I have tested this and it works.
public class Main {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
final String pathPartOne = "test/com";
final String pathPartTwo = "/MyResources";
String pathName = "C:\\Users\\Jonathan\\Desktop\\test.jar";
JarTest test = new JarTest();
final File jarFile = new File(pathName);
if(jarFile.isFile()) { // Run with JAR file
final JarFile jar = new JarFile(jarFile);
final Enumeration<JarEntry> entries = jar.entries(); //gives ALL entries in jar
while(entries.hasMoreElements()) {
final String name = entries.nextElement().getName();
if (name.startsWith(pathPartOne+pathPartTwo + "/")) { //filter according to the path
if(name.contains("."))//has extension
{
String relavtivePath = name.substring(pathPartOne.length()+1);
String fileName = name.substring(name.lastIndexOf('/')+1);
System.out.println(relavtivePath);
System.out.println(fileName);
test.copyFile(relavtivePath, "C:\\Users\\Jonathan\\Desktop\\" + fileName);
}
}
}
jar.close();
}
}
}
Hope that helps.
The problem here is different File Systems. C:/Users/Cam/Desktop/mtd.jar is a File in the WindowsFileSystem. Since it is a file, and not a directory, you cannot access a subdirectory inside the file; C:/Users/Cam/Desktop/mtd.jar/resources is only a valid Path if mtd.jar is actually a directory instead of a file.
In order to access something on a different file system, you must use the path from the root of that file system. For example, if you have a file in D:\dir1\dir2\file, you cannot reach it using a path that begins with C:\ (symbolic links not withstanding); you must use a path that starts at the root of that file system D:\.
A jar file is just a file. It can be located anywhere within a file system, and can be moved, copied or deleted like any regular file. However, it contains within itself its own file system. There is no windows path that can be used to reference any file inside the jar's file system, just like no path starting at C:\ can reference any file within the D:\ file system.
In order to access the contents of a jar, you must open the jar as a ZipFileSystem.
// Autoclose the file system at end of try { ... } block.
try(FileSystem zip_fs = FileSystems.newFileSystem(pathToZipFile, null)) {
}
Once you have zip_fs, you can use zip_fs.getPath("/path/in/zip"); to get a Path to a file within it. This Path object will actually be a ZipFileSystemProvider path object, not a WindowsFileSystemProvider path object, but otherwise it is a Path object that can be opened, read from, etc., at least until the ZipFileSystem is closed. The biggest differences are that path.getFileSystem() will return the ZipFileSystem, and that resolve() and relativize() cannot use path objects where getFileSystem() returns different file systems.
When your project ran from Eclipse, all the resources were in the WindowsFileSystem, so walking the file system tree and copying the resources was straight forward. When your project ran from a jar, the resources were not in the default file system.
Here is a Java class that will copy resources to an installation directory. It will work in Eclipse (with all the resources as individual files), as well as when the application is packaged into a jar.
public class Installer extends SimpleFileVisitor<Path> {
public static void installResources(Path dst, Class<?> cls, String root) throws URISyntaxException, IOException {
URL location = cls.getProtectionDomain().getCodeSource().getLocation();
if (location.getProtocol().equals("file")) {
Path path = Paths.get(location.toURI());
if (location.getPath().endsWith(".jar")) {
try (FileSystem fs = FileSystems.newFileSystem(path, null)) {
installResources(dst, fs.getPath("/" + root));
}
} else {
installResources(dst, path.resolve(root));
}
} else {
throw new IllegalArgumentException("Not supported: " + location);
}
}
private static void installResources(Path dst, Path src) throws IOException {
Files.walkFileTree(src, new Installer(dst, src));
}
private final Path target, source;
private Installer(Path dst, Path src) {
target = dst;
source = src;
}
private Path resolve(Path path) {
return target.resolve(source.relativize(path).toString());
}
#Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
Path dst = resolve(dir);
Files.createDirectories(dst);
return super.preVisitDirectory(dir, attrs);
}
#Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Path dst = resolve(file);
Files.copy(Files.newInputStream(file), dst, StandardCopyOption.REPLACE_EXISTING);
return super.visitFile(file, attrs);
}
}
Called as:
Path dst = Paths.get("C:\\Program Files\\mtd");
Installer.installResources(dst, Game.class, "resources");
I FINALLY FOUND THE ANSWER
I don't want to type out a big, long explanation but for anyone looking for the solution, here it is
`
//on startup
installDir("");
for (int i = 0; i < toInstall.size(); i++) {
File f = toInstall.get(i);
String deepPath = f.getPath().replace(f.getPath().substring(0, f.getPath().lastIndexOf("resources") + "resources".length() + 1), "");
System.out.println(deepPath);
System.out.println("INSTALLING: " + deepPath);
installDir(deepPath);
System.out.println("INDEX: " + i);
}
public void installDir(String path) {
System.out.println(path);
final URL url = getClass().getResource("/resources/" + path);
if (url != null) {
try {
final File apps = new File(url.toURI());
for (File app : apps.listFiles()) {
System.out.println(app);
System.out.println("copying..." + app.getPath() + " to " + pfFolder.getPath());
String deepPath = app.getPath().replace(app.getPath().substring(0, app.getPath().lastIndexOf("resources") + "resources".length() + 1), "");
System.out.println(deepPath);
try {
File f = new File(resources.getPath() + "/" + deepPath);
if (getExtention(app) != null) {
FileOutputStream resourceOS = new FileOutputStream(f);
byte[] byteArray = new byte[1024];
int i;
InputStream classIS = getClass().getClassLoader().getResourceAsStream("resources/" + deepPath);
//While the input stream has bytes
while ((i = classIS.read(byteArray)) > 0)
{
//Write the bytes to the output stream
resourceOS.write(byteArray, 0, i);
}
//Close streams to prevent errors
classIS.close();
resourceOS.close();
} else {
System.out.println("new dir: " + f.getPath() + " (" + toInstall.size() + ")");
f.mkdir();
toInstall.add(f);
System.out.println(toInstall.size());
}
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (URISyntaxException ex) {
// never happens
}
}
}`

Programmatically creating jar file

I am running Mac OSX Mavericks. Right now I am creating a JAR file from a folder (org, the package). When I use this code from here:
public void run() throws IOException
{
Manifest manifest = new Manifest();
manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
JarOutputStream target = new JarOutputStream(new FileOutputStream("/Users/username/Library/Application Support/VSE/temp/output.jar"), manifest);
add(new File("/Users/username/Library/Application Support/VSE/temp/org"), target);
target.close();
}
private void add(File source, JarOutputStream target) throws IOException
{
BufferedInputStream in = null;
try
{
if (source.isDirectory())
{
String name = source.getPath().replace("\\", "/");
if (!name.isEmpty())
{
if (!name.endsWith("/"))
name += "/";
JarEntry entry = new JarEntry(name);
entry.setTime(source.lastModified());
target.putNextEntry(entry);
target.closeEntry();
}
for (File nestedFile: source.listFiles())
add(nestedFile, target);
return;
}
JarEntry entry = new JarEntry(source.getPath().replace("\\", "/"));
entry.setTime(source.lastModified());
target.putNextEntry(entry);
in = new BufferedInputStream(new FileInputStream(source));
byte[] buffer = new byte[1024];
while (true)
{
int count = in.read(buffer);
if (count == -1)
break;
target.write(buffer, 0, count);
}
target.closeEntry();
}
finally
{
if (in != null)
in.close();
}
}
When I extract the JAR file, There is a META-INF folder, but instead of having the org folder in the extracted jar, I have my Users folder copied into it (except because of it's size, its wasn't filled with all my stuff and my application crashed). I'm expecting this is because the code was written for a Windows system, and the differences with the filesystem (such as \ or /). How would I make the code include only the "org" directory, and not everything leading up to it?
Provided you use Java 7+ you may easily do this by using one of my packages in combination with the zip filesystem provider of the JDK to create it:
private static final Map<String, ?> ENV = Collections.singletonMap("create", "true");
public void run()
throws IOException
{
final Path zipPath = Paths.get("/Users/username/Library/Application Support/VSE/temp/output.jar");
final Path srcdir = Paths.get("/Users/username/Library/Application Support/VSE/temp/org");
final URI uri = URI.create("jar:" + zipPath.toUri());
Files.deleteIfExists(zipPath);
try (
final FileSystem zipfs = FileSystems.newFileSystem(uri, ENV);
) {
copyManifest(zipfs);
copyDirectory(srcdir, zipfs);
}
}
private void copyManifest(final FileSystem zipfs)
throws IOException
{
final Manifest manifest = new Manifest();
manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
Files.createDirectory(zipfs.getPath("META-INF/");
try (
final OutputStream out = Files.newOutputStream(zipfs.getPath("META-INF/MANIFEST.MF"));
) {
manifest.write(out);
}
}
private void copyDirectory(final Path srcdir, final FileSystem zipfs)
{
final String lastName = srcdir.getFileName().toString();
final Path dstDir = zipfs.getPath(lastName);
Files.createDirectory(dstDir);
MoreFiles.copyRecursive(srcDir, dstDir, RecursionMode.FAIL_FAST);
}

How can i chage name of image using java while uploading and save in folder? [duplicate]

This question already has answers here:
Recommended way to save uploaded files in a servlet application
(2 answers)
Closed 6 years ago.
<body>
<form method="post" action="DemoServlet" enctype="multipart/form-data" name="form1">
<input type="file" name="file" />
Image_Name:<input type="text" name="file"/>
<input type="submit" value="Go"/>
</form>
</body>
this is my index.jsp page.
This Servlet is DemoServlet when user click on submit button it will go here.while in jsp page suppose Image_Name given by user is IPL and actual name of image is funny.jpg then while saving the image it should store as IPL.png,here i'm able to upload image correctly with funny.jpg,but i need to save image as given name in text field of index.jsp page
public class DemoServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Date date = new Date();
response.setContentType("text/html");
PrintWriter out = response.getWriter();
boolean isMultiPart = ServletFileUpload.isMultipartContent(request);
if (isMultiPart) {
ServletFileUpload upload = new ServletFileUpload();
try {
FileItemIterator itr = upload.getItemIterator(request);
while (itr.hasNext()) {
FileItemStream item = itr.next();
if (item.isFormField()) {
String fieldname = item.getFieldName();
InputStream is = item.openStream();
byte[] b = new byte[is.available()];
is.read(b);
String value = new String(b);
response.getWriter().println(fieldname + ":" + value + "</br>");
} else {
String TempPath = getServletContext().getRealPath("");
String path = TempPath.substring(0, TempPath.indexOf("build"));
if (FileUpload.processFile(path, item)) {
out.println("File Uploaded on:" + date + "<br>");
response.getWriter().println("Image Upload Successfully");
} else {
response.getWriter().println("Failed.....Try again");
}
}
}
} catch (FileUploadException fue) {
fue.printStackTrace();
}
}
}
}
and this is java class
public class FileUpload {
public static boolean processFile(String path, FileItemStream item) {
try {
File f = new File(path + File.separator + "web/images");
if (!f.exists()) {
f.mkdir();
}
File savedFile = new File(f.getAbsolutePath() + File.separator + item.getName());
FileOutputStream fos = new FileOutputStream(savedFile);
InputStream is = item.openStream();
int x = 0;
byte[] b = new byte[1024];
while ((x = is.read(b)) != -1) {
fos.write(b, 0, x);
}
fos.flush();
fos.close();
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
}
Could anybody guide me how to change this dynamically.Thanks in advance.
I don't know how Servlet's and the like work however i can give you a rundown of what you need to do.
In DemoServlet you need to take in the input of the Image_Name field and make that one of your parameters of FileUpload
public static boolean processFile(String path, FileItemStream item, String fileName){
//Method Code
}
Because currently your processFile method is taking the name of the file from your FileItemStream. You need to change it from that to your actual fileName
File savedFile = new File(f.getAbsolutePath() + File.separator + item.getName());
to
File savedFile = new File(f.getAbsolutePath() + File.separator + fileName + ".png");
You can change the name of image in your java class code.
public class FileUpload {
public static boolean processFile(String path, FileItemStream item , String name) {
try {
File f = new File(path + File.separator + "web/images");
if (!f.exists()) {
f.mkdir();
}
File savedFile = new File(f.getAbsolutePath() + File.separator + item.getName()); // instead of item.getName() you can give your name.
FileOutputStream fos = new FileOutputStream(savedFile);
InputStream is = item.openStream();
int x = 0;
byte[] b = new byte[1024];
while ((x = is.read(b)) != -1) {
fos.write(b, 0, x);
}
fos.flush();
fos.close();
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
you will have to pass the file name in the method.
instead of item.getName() you can give your name.
List fileItems = upload.parseRequest(request);
Iterator i = fileItems.iterator();
System.out.println("In >>>>>>>>>>>>>>> :: "+fileItems);
while(i.hasNext()){
FileItem fi = (FileItem) i.next();
System.out.println("Val <<<<>>>>>>:: "+fi);
if(fi.isFormField()){
String fieldName = fi.getFieldName();
String val = fi.getString();
System.out.println(fieldName+" :: Val :: "+val);
}else{
String fileName = fi.getName();
String root = getServletContext().getRealPath("/");
File path = new File(root+"/uploads");
if (!path.exists()) {
boolean status = path.mkdir();
}
File uploadFile = new File(path+"/"+fileName);
fi.write(uploadFile);
}
In the code above you can change the file name at any time and it will automatically save with this name.
//How does not work in this way?Please tell me another way.
import java.io.File;
public class RenameFileExample {
public static void main(String[] args)
{
File oldfile =new File("oldfile.txt");
File newfile =new File("newfile.txt");
File file = new File("oldfilename.png");
file.renameTo(new File("newfilename.png"));
System.out.println("Rename To:"+file.getName());
if(oldfile.renameTo(newfile)){
System.out.println("Rename succesful");
}else{
System.out.println("Rename failed");
}
}
}

Categories