URL urlImage = new URL(candidateImagePath);
BufferedImage image = ImageIO.read(urlImage);
String imageName = urlImage.getFile().split("/")[3];
String pathImage = messageSource.getMessage("consultant.image", null, Locale.ENGLISH)+messageSource.getMessage("system.slash", null, Locale.ENGLISH)+candidateid;
File fileDir = new File(pathImage);
fileDir.mkdirs();
ImageIO.write(image, "jpg" ,new File(pathImage+messageSource.getMessage("system.slash", null, Locale.ENGLISH)+imageName));
I am trying to get an image uploaded by iphone guys to a temporary url .
I read the image and write it to my desired location which is 'pathImage'.
Till here everything works fine.
I want to delete the temporary file in the url.
I want to know how can I delete the image when the url is given in java. Kindly help on this .
You need to write a wrapper on target URL, which will simply delete the file passed as a query string like
http://your_temp_url/deleteimage?file=your_temp_file_name
in deleteimage you will code like this
private void deletefile(String file)
{
File f1 = new File(file);
boolean success = f1.delete();
if (!success){
out.println("Deletion failed.");
}else{
out.println("File deleted.");
}
This is just one approach to delete the image located on remote machine.
new File(url.toURI()).delete();
should do the trick.
example:
URL url=getClass().getResource("/someresources/resourceFile.txt");
File f=new File(url.toURI());
f.delete();
Related
I am trying to create a temp file and generate a file name and then save a multipart file. I am using Spring Boot and the following code is working in local. But in heroku or docker it is throwing FileNotFoundException; So how to create a temp directory and save a file inside that temp directory in docker/heroku? Or what is the best way to save multipart file to temp folder in server? Anybody can help me? Thanks in advance.
File tempDirectory = new File(new File(System.getProperty("java.io.tmpdir")), "files");
if (!tempDirectory.exists()) {
tempDirectory.mkdir();
}
String filePath = new File(tempDirectory.getAbsolutePath() + "/temp.pdf").getAbsolutePath();
File tempDirectory = new File(new File(System.getProperty("java.io.tmpdir")), "files");
if(tempDirectory.exists()){
System.out.println("something");
}else{
tempDirectory.mkdirs();
}
File file = new File(tempDirectory.getAbsolutePath()+"/abcd.txt");
if(!file.exists()){
file.createNewFile();
}
String file2= new File(tempDirectory.getAbsolutePath()+"/something.txt").getAbsolutePath();
System.out.println(file2);
Works totally fine at my end. The only problem you might be having is
String filePath = new File(tempDirectory.getAbsolutePath() + "/temp.exe").getAbsolutePath();
This doesn't create the file in the temp directory you have created. It just returns the absolute path if it was to be saved in the directory mentioned. This might be the reason you are getting not found error. Try actually saving by using
file.transferTo(wherefileneedstobesavedlocation);
In my program, I want to sent some files from client to server using socket programming. I'm using the void setMultiSelectionEnabled(boolean b) method so I can choose more than 1 file, but it gives me an error when i try to get the path of the file. Here's my code:
JFileChooser choose = new JFileChooser();
choose.setAcceptAllFileFilterUsed(false);
choose.addChoosableFileFilter(new FileNameExtensionFilter("Images", "jpg", "png", "jpeg"));
choose.setAcceptAllFileFilterUsed(true);
choose.setMultiSelectionEnabled(true);
File[] f = choose.getSelectedFiles();
choose.showOpenDialog(this);
String filePath = f.getAbsolutePath();
String fname = f.getName();
Client_ftp cli = new Client_ftp();
if(cli.kirim(filePath, fname)) {
jLabel1.setText("Success. .");
} else {
jLabel1.setText("failed");
}
f is an array. You'll need to index the array before calling the getAbsolutePath() method for each File in f. Make sure to check for null prior to doing so.
Example: f[0].getAbsolutePath();
I want to upload files and save them into specific directory.And i am new to files concept.When i uploading files from my page they are saved in another directory(C:\Users\ROOTCP~1\AppData\Local\Temp\multipartBody989135345617811478asTemporaryFile) and not in specified directory.I am unable to set it.Please help me in finding a solution.For all help thanks in advance.
public static Result uploadHoFormsByHeadOffice() throws Exception {
Logger.info("#C HoForms -->> uploadHoFormsByHeadOffice() -->> ");
final String basePath = System.getenv("INVOICE_HOME");
play.mvc.Http.MultipartFormData body = request().body()
.asMultipartFormData(); // get Form Body
StringBuffer fileNameString = new StringBuffer(); // to save file path
// in DB
String formType = body.asFormUrlEncoded().get("formType")[0];// get formType from select Box
FilePart upFile = body.getFile("hoFiles");//get the file details
String fileName = upFile.getFilename();//get the file name
String contentType = upFile.getContentType();
File file = upFile.getFile();
//fileName = StringUtils.substringAfterLast(fileName, ".");
// path to Upload Files
File ftemp= new File(basePath +"HeadOfficeForms\\"+formType+"");
//File ftemp = new File(basePath + "//HeadOfficeForms//" + formType);
File f1 = new File(ftemp.getAbsolutePath());// play
ftemp.mkdirs();
file.setWritable(true);
file.setReadable(true);
f1.setWritable(true);
f1.setReadable(true);
//HoForm.create(fileName, new Date(), formType);
Logger.info("#C HoForms -->> uploadHoFormsByHeadOffice() <<-- Redirecting to Upload Page for Head Office");
return redirect(routes.HoForms.showHoFormUploadPage());
}
}
I really confused why the uploaded file is saved in this(C:\Users\ROOTCP~1\AppData\Local\Temp\multipartBody989135345617811478asTemporaryFile) path.
You're almost there.
File file = upFile.getFile(); is the temporary File you're getting through the form input. All you've got to do is move this file to your desired location by doing something like this: file.renameTo(ftemp).
Your problem in your code is that you're creating a bunch of files in memory ftemp and f1, but you never do anything with them (like writing them to the disk).
Also, I recommend you to clean up your code. A lot of it does nothing (aforementioned f1, also the block where you're doing the setWritable's). This will make debugging a lot easier.
I believe when the file is uploaded, it is stored in the system temporary folder as the name you've provided. It's up to you to copy that file to a name and location that you prefer. In your code you are creating the File object f1 which appears to be the location you want the file to end up in.
You need to do a file copy to copy the file from the temporary folder to the folder you want. Probably the easiest way is using the apache commons FileUtils class.
File fileDest = new File(f1, "myDestFileName.txt");
try {
FileUtils.copyFile(ftemp, fileDest);
}
catch(Exception ex) {
...
}
Hi i have a small problem with URL, i need to verify PDF file, which i must first download. I use this code below:
URL TestURL2 = new URL("file:///C:/Users/Ludek/Downloads/katalog_dokument_53766_test.pdf");
BufferedInputStream TestFile = new BufferedInputStream(TestURL2.openStream());
PDFParser TestPDF2 = new PDFParser(TestFile);
TestPDF2.parse();
String TestText2 = new PDFTextStripper().getText(TestPDF2.getPDDocument());
try {
assertTrue(TestText2.contains("Text PDF"));
System.out.println("it's OK");
} catch (Error e) {
verificationErrors.append(e.toString());
System.out.println("not OK!!!");
}
But numbers 53766 in file name are everytime different. Can i use some wildcard or something else?
Can anyone advise me please? Thanks
If there is only one file in your folder - your pdf, you can use a code similar to this one:
string[] files = System.IO.Directory.GetFiles(#"C:/Users/Ludek/Downloads/", "*.pdf");
Before the download process, you can always delete all files from the folder or even always specify a unique download folder, this way only your file will be there and you can be sure when you verify it.
I used this solution, it's simple and works.
File f = new File("C:/Users/Ludek/Downloads/");
FilenameFilter textFilter = new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(".pdf");
}
};
File[] files = f.listFiles(textFilter);
for (File file : files) {
String URL = file.getCanonicalPath().substring(25);
URL TestURL2 = new URL("file:C:/Users/Ludek/Downloads/" + URL);
i want to store uploaded file in a specific location in java. if i upload a.pdf then i want it to store this at "/home/rahul/doc/upload/". i went through some questions and answers of stack overflow but i am not satisfied with solutions.
i am working with Play Framework 2.1.2. i am not working with servlet.
i am uploading but it is storing file into temp directory but i want that file store into a folder as not a temp file i want that file like a.pdf in folder not like temp file.
public static Result upload() {
MultipartFormData body = request().body().asMultipartFormData();
FilePart filePart1 = body.getFile("filePart1");
File newFile1 = new File("path in computer");
File file1 = filePart1.getFile();
InputStream isFile1 = new FileInputStream(file1);
byte[] byteFile1 = IOUtils.toByteArray(isFile1);
FileUtils.writeByteArrayToFile(newFile1, byteFile1);
isFile1.close();
}
but i am not satisfied with this solution and i am uploading multiple doc files.
for eg. i upload one doc ab.docx then after upload it is storing temp directory and file is this:
and it's location is this: /tmp/multipartBody5886394566842144137asTemporaryFile
but i want this: /upload/ab.docx
tell me some solution to fix this.
Everything's correct as a last step you need to renameTo the temporary file into your upload folder, you don't need to play around the streams it's as simple as:
public static Result upload() {
Http.MultipartFormData body = request().body().asMultipartFormData();
FilePart upload = body.getFile("picture");
if (upload != null) {
String targetPath = "/your/target/upload-dir/" + upload.getFilename();
upload.getFile().renameTo(new File(targetPath));
return ok("File saved in " + targetPath);
} else {
return badRequest("Something Wrong");
}
}
BTW you should implement some checking if targetPath doesn't exist to prevent errors and/or overwrites. Typical approach is incrementing the file name if file with the same name already exists, for an example sending a.pdf three times should save the files as a.pdf, a_01.pdf, a_02.pdf, etc.
i just completed it. My solution is working fine.
My solution of uploading multiple files is :
public static Result up() throws IOException{
MultipartFormData body = request().body().asMultipartFormData();
List<FilePart> resourceFiles=body.getFiles();
InputStream input;
OutputStream output;
File part1;
String prefix,suffix;
for (FilePart picture:resourceFiles) {
part1 =picture.getFile();
input= new FileInputStream(part1);
prefix = FilenameUtils.getBaseName(picture.getFilename());
suffix = FilenameUtils.getExtension(picture.getFilename());
part1=new File("/home/rahul/Documents/upload",prefix+"."+suffix);
part1.createNewFile();
output = new FileOutputStream(part1);
IOUtils.copy(input, output);
Logger.info("Uploaded file successfully saved in " + part1.getAbsolutePath());
}