I try to use the official Dropbox API for uploading a zip file to my account. My project is a desktop application (standard Java). My code looks like this:
public void uploadZipFile(File file) throws Exception {
FileInputStream fis = new FileInputStream(file);
try {
getClient(accessToken).uploadFile("/" + file.getName(), DbxWriteMode.add(), file.length(), fis);
} finally {
fis.close();
}
}
private DbxClient getClient(String accessToken) {
DbxRequestConfig dbxRequestConfig = new DbxRequestConfig(Constants.APP_NAME, Locale.getDefault().toString());
return new DbxClient(dbxRequestConfig, accessToken);
}
And I call it:
File zipFile = new File("C:\\Test\\MyFile.zip");
try {
uploadZipFile(zipFile);
} catch (Exception e) {
e.printStackTrace();
}
The file is transferred without any problems but then I want to delete the file after synchronization:
File zipFile = new File("C:\\Test\\MyFile.zip");
try {
uploadZipFile(zipFile);
System.out.println(zipFile.delete());
} catch (Exception e) {
e.printStackTrace();
}
The file is transferred successfully again, but the file still exists in the local file system and the delete method returns false.
Related
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
}
}
I am using apache common library for connecting to FTP with Android app.
Now I want to upload a file from internal storage to FTP server and I get this reply from getReplyString() method.
And I get this msg
553 Can't open that file: Permission denied
//Write file to the internal storage
String path = "/sdcard/";
File file = new File(path, fileName);
FileOutputStream stream = null;
try {
stream = new FileOutputStream(file);
stream.write(jsonObject.toString().getBytes());
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// Read the file from resources folder.
try {
File file1 = new File(path, fileName);
Log.d("path",file1.getPath());
BufferedInputStream in = new BufferedInputStream (new FileInputStream (file1.getPath()));
client.connect(FTPHost);
client.login(FTPUserName, FTPPassword);
client.enterLocalPassiveMode();
client.setFileType(FTP.BINARY_FILE_TYPE);
// Store file to server
Log.d("reply",client.getReplyString());
boolean res = client.storeFile("/"+fileName, in);
Log.d("reply",client.getReplyString());
Log.d("result",res+"");
client.logout();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
client.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
My web app is made on Spring MVC. I have a method where the user can upload PDFs
.
The I am sending the file as mutlipart file to the server. Every time the user uploads.
All what I want is to send the files as attachments in that email.
My code
private File prepareAttachment(final MultipartFile mFile) {
File file = new File(System.getProperty("java.io.tmpdir") + System.getProperty("file.separator") + mFile.getOriginalFilename());
try {
if(file.exists()) {
file.delete();
}
mFile.transferTo(file);
} catch (FileNotFoundException fnfE) {
file.delete();
LOG.error(" file was not found.", fnfE);
} catch (IOException ioE) {
file.delete();
LOG.error("file has failed to upload.", ioE);
}
return file;
}
calling the method to prepare the attachment:
MimeMessagePreparator preparator = new MimeMessagePreparator() {
#Override
public void prepare(final MimeMessage mimeMessage) throws Exception {
File file = prepareAttachment(form.getFile());
File file2 = prepareAttachment(form.getFile2());
MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true);
message.addAttachment(form.getFile().getOriginalFilename(), file);
message.addAttachment(form.getFile2().getOriginalFilename(), file2);
Getting exception:
2017-08-28 15:10:59,549 ERROR com.menards.requestForms.business.service.EmailService - file has failed to upload.
java.io.IOException: Destination file [C:\opt\tcserver\main\temp] already exists and could not be deleted
at org.springframework.web.multipart.commons.CommonsMultipartFile.transferTo(CommonsMultipartFile.java:160) ~[spring-web-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at com.menards.requestForms.business.service.EmailService.prepareAttachment(EmailService.java:552) ~[classes/:?]
this will work perfectly if I comment out adding the second file :(
message.addAttachment(form.getFile2().getOriginalFilename(), file2);
any advise?
Generally, you shouldn't let your users determine the path of a file that you're creating on your server - it introduces a lot of security vulnerabilities. In this case, they may be attempting to create a temp file that has the same as some other file in your temp directory, potentially one that has nothing to do with your current application. File.createTempFile ensures that it creates a file with a unique name on each invocation.
It's also good practice to clean up temp files as soon as you're finished with them, so you don't have to worry about maintaining state on your server between method calls. This can sometimes create code that's a bit busy with catch/finally blocks, but it's worth it to avoid waking up at 3 AM to a hard disk that's full of garbage temp files.
I'd implement this roughly as:
private File prepareAttachment(final MultipartFile mFile) throws IOException {
File tmp = null;
try {
tmp = File.createTempFile("upload", ".tmp");
mFile.transferTo(tmp);
return tmp;
} catch (IOException ioE) {
if (tmp != null) {
tmp.delete();
}
LOG.error("file has failed to upload.", ioE);
throw ioE;
}
}
MimeMessagePreparator preparator = new MimeMessagePreparator() {
#Override
public void prepare(final MimeMessage mimeMessage) throws Exception {
File file1 = null;
File file2 = null;
try {
file1 = prepareAttachment(form.getFile());
file2 = prepareAttachment(form.getFile2());
MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true);
message.addAttachment(form.getFile().getOriginalFilename(), file1);
message.addAttachment(form.getFile2().getOriginalFilename(), file2);
// do your other stuff
} catch (IOException e) {
// some sort of error-handling, probably returning a message with an error status
} finally {
if (file1 != null) {
file1.delete();
}
if (file2 != null) {
file2.delete();
}
}
}
};
New edit:
Now i found the cause, it is because there are two servers and it write into temp folder in 1st server and try to read from the 2nd one. But I still didn't find a solution for this unless write to Amazon S3 and read from there.
I tried to export csv with struts2 action. However if I tried to export 10 times i can only succeed once, all the others failed with File not found exception (if I refresh the link again, the file can be downloaded). Here is my code:
public String exportFile(String fileName) {
File exportFile = null;
try {
if (CollectionUtils.isEmpty(receipts)) {
return "";
}
exportFile = File.createTempFile(fileName, ".csv");
exportFile.deleteOnExit();
try (BufferedWriter fw = new BufferedWriter(new FileWriter(exportFile))) {
try {
fw.write("test");
} finally {
fw.close();
}
}
return exportFile.getPath();
} catch (Exception ex) {
logger.error("Error exporting report. ", ex.getMessage());
}
return "";
}
String getStreamFromPath(String filePath) {
try {
File downloadFile = new File(filePath);
fileInputStream = new FileInputStream(downloadFile);
return SUCCESS;
} catch (IOException e) {
log.error(e.getMessage(), e);
return ERROR;
}
}
This is really weird, when i test in another server it works totally fine. Any ideas?
Like in the method i have attached i have used practiceData.txt i am getting same results while using just practiceData in file constructor so is it ok to use file without any extension or txt is better?
private void saveData(String data) {
File file = new File(this.getFilesDir(), "practiceData.txt");
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(file);
fileOutputStream.write(data.getBytes());
saveStatus = "Data was successfully saved.";
} catch (java.io.IOException e) {
e.printStackTrace();
saveStatus = "Error occurred: " + e.toString();
} finally {
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
It doesn't matter what file extension you use, it just tells the OS how to open the file. So yes, you can use no extension and it will work just as well.
If you intend the file to be opened manually via another application, it may be helpful to use a standard extension however.