I am uploading image from url on ftp by this code.
Image uploaded successful but when i try to resize uploaded image get error as the follows.
String imageUrl = "http://www.totaldesign.ir/wp-content/uploads/2014/11/hamayesh.jpg";
FTPClient ftpClient = new FTPClient();
ftpClient.connect(ftp_server, ftp_port);
ftpClient.login(ftp_user, ftp_pass);
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
ftpClient.enterLocalPassiveMode();
// APPROACH #2: uploads second file using an OutputStream
URL url = new URL(imageUrl);
//**************select new name for image***********/
//get file extention
File file = new File(imageUrl);
String ext = getFileExtension(file);
//get file name from url
String fileName = imageUrl.substring(imageUrl.lastIndexOf('/') + 1, imageUrl.length());
String fileNameWithoutExtn = fileName.substring(0, fileName.lastIndexOf('.'));
//create new image name for upload
String img_name = "simjin.com_" + fileNameWithoutExtn;
//get current year time for image upload dir
Date date = new Date();
DateFormat yeae = new SimpleDateFormat("yyyy");
String current_year = yeae.format(date);
//create dirs if not exist
ftpClient.changeWorkingDirectory(current_year);
int dirCode = ftpClient.getReplyCode();
if (dirCode == 550) {
//create dir
ftpClient.makeDirectory(current_year);
System.out.println("created folder: " + current_year);
}
//get current month time for image upload dir
DateFormat month = new SimpleDateFormat("MM");
String current_month = month.format(date);
//create dirs if not exist
ftpClient.changeWorkingDirectory("/" + current_year + "/" + current_month);
dirCode = ftpClient.getReplyCode();
if (dirCode == 550) {
//create dir
ftpClient.makeDirectory("/" + current_year + "/" + current_month);
System.out.println("created folder: " + "/" + current_year + "/" + current_month);
}
String uploadDir = "/" + current_year + "/" + current_month;
//rename image file if exist
boolean exists;
String filePath = uploadDir + "/" + img_name + "." + ext;
exists = checkFileExists(filePath);
System.out.println("old file path=> " + exists);
//Rename file if exist
int i = 0;
while (exists) {
i++;
img_name = "simjin.com_" + fileNameWithoutExtn + i;
filePath = uploadDir + "/" + img_name + "." + ext;
exists = checkFileExists(filePath);
//break loop if file dont exist
if (!exists) {
break;
}
}
System.out.println("new file path=> " + filePath);
//set image name in array for return
result[0] = img_name;
//*************end select new name for image**********/
System.out.println("ftpClinet Replay Code=> " + ftpClient.getStatus());
//Start uploading second file
InputStream inputStream = new BufferedInputStream(url.openStream());
OutputStream outputStream = ftpClient.storeFileStream(filePath);
System.out.println("outputStream Status=> " + outputStream);
byte[] bytesIn = new byte[10240];
int read = 0;
while ((read = inputStream.read(bytesIn)) != -1) {
outputStream.write(bytesIn, 0, read);
}
inputStream.close();
outputStream.close();
boolean completed = ftpClient.completePendingCommand();
after success upload. I want to resize image by thumbnailator:
if (completed) {
System.out.println("The file is uploaded successfully.");
String new_img_name = uploadDir + "/" + img_name + "-150x150" + "." + ext;
OutputStream os = ftpClient.storeFileStream(filePath);
Thumbnails.of(image_url).size(150, 150).toOutputStream(os);
}
in this section get this error:
OutputStream cannot be null
Where is my wrong? And how to fix it?
Related
Hello i want to make a http server with nanohttpd that shows installed apps, and convert them to apk and download. I can list but how can i download the app i select
List<ApplicationInfo> packages = packageManager.getInstalledApplications(PackageManager.GET_META_DATA;
for (ApplicationInfo packageInfo : packages) {
String name = String.valueOf(packageManager.getApplicationLabel(packageInfo));
if (name.isEmpty()) {
name = packageInfo.packageName;
}
Drawable icon = packageManager.getApplicationIcon(packageInfo);
String apkPath = packageInfo.sourceDir;
apps.add(new App(name, apkPath, icon, packageInfo.packageName));
}
if (method.equals(Method.GET)) {
for (App file : apps) {
answer += "<a href=\"" + file.getAppName()
+ "\" alt = \"\">" + file.getAppName()
+ "</a><br>";
}
Ok, I basicly take the url after list the apps and check which appname equal to url after that i start to download it like that
if (method.equals(Method.GET)) {
if (a) {
answer = "<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; " +
"charset=utf-8\"><title> HTTP File Browser</title>";
for (App file : appShare) {
answer += "<a href=\"" + file.getAppName()
+ "\" alt = \"\">" + file.getAppName()
+ "</a><br>";
}
answer += "</head></html>";
if(blabla.equals(header.get("referer"))){
a=false;
}
} else {
for (int i = 0; i < appShare.size(); i++) {
if (appShare.get(i).getAppName().equals(appnames))
arrayC = i;
}
answer = "<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; " +
"charset=utf-8\"><title> Download " + appShare.get(arrayC).getAppName() + "</title>";
// serve file download
InputStream inputStream;
Response response = null;
if (mStatusUpdateListener != null) {
mStatusUpdateListener.onDownloadingFile(
new File(appShare.get(arrayC).getApkPath()), false);
}
try {
inputStream = new FileInputStream(
new File(appShare.get(arrayC).getApkPath()));
response = new DownloadResponse(
new File(appShare.get(arrayC).getApkPath()), inputStream);
} catch (Exception e) {
e.printStackTrace();
} response.addHeader(
"Content-Disposition", "attachment; filename=" + appShare.get(arrayC).getAppName()+".apk");
return response;
}
i am creating a .jar file to plug into a java connector on bpm.
the idea is for the .jar to generate a pdf from html which is using images from a Image folder and send as an email attachment.
the PDF sends ok with the html and the images when ran from eclipse, soon as i export the .jar and try to use it outside of eclipse it doesnt show the images
System.out.println("I am about to get resource image001");
BufferedImage imageone = ImageIO.read(new FileInputStream("Images/image001.jpg"));
File outputfile = new File("Images/image001.jpg");
ImageIO.write(imageone, "jpg", outputfile);
System.out.println("image 1 " + outputfile.toURL());
String one = "Images/image001.jpg";
System.out.println("got image 1");
System.out.println("I am about to get rousrce image002");
//BufferedImage bufferedImage2 = ImageIO.read(jamesNew.class.getResource("/Images/image002.gif"));
BufferedImage imagwtwo = ImageIO.read(new FileInputStream("Images/image002.gif"));
File outputfile1 = new File("image002.gif");
ImageIO.write(imagwtwo, "gif", outputfile1);
System.out.println("image 2 " + outputfile1.toURL());
String two = "Images/image002.gif";
System.out.println("got image 2");
System.out.println("I am about to get rousrce image003");
//BufferedImage bufferedImage3 = ImageIO.read(jamesNew.class.getResource("/Images/image003.gif"));
BufferedImage imagwthree = ImageIO.read(new FileInputStream("Images/image003.gif"));
File outputfile2 = new File("image003.gif");
ImageIO.write(imagwthree, "gif", outputfile2);
System.out.println("image 3 " + outputfile2.toURL());
String three = "Images/image003.gif";
System.out.println("got image 3");
System.out.println("I am about to get rousrce image004");
//BufferedImage bufferedImage4 = ImageIO.read(jamesNew.class.getResource("/Images/image006.gif"));
BufferedImage imagefour = ImageIO.read(new FileInputStream("Images/image006.gif"));
File outputfile3 = new File("image006.gif");
ImageIO.write(imagefour, "gif", outputfile3);
System.out.println("image 4 " + outputfile3.toURL());
String four = "Images/image006.gif";
System.out.println("got image 4");
System.out.println("I am about to get rousrce image005");
//BufferedImage bufferedImage5 = ImageIO.read(jamesNew.class.getResource("/Images/logo1.png"));
BufferedImage imagwfive = ImageIO.read(new FileInputStream("Images/logo1.png"));
File outputfile4 = new File("logo1.png");
ImageIO.write(imagwfive, "png", outputfile4);
System.out.println("image 5 " + outputfile4.toURL());
String five = "Images/logo1.png";
System.out.println("got image 5");
System.out.println("CLASS PATHS SET..........");
String named = null;
String total = null;
String completehtml1 = null;
String style = "<style type=\""+"text/css" + "\" >" + ".centerImage { text-align:center; display:block; } </style>";
String feed = "<html><body>";
System.out.println("STRINGS SET..........");
completehtml = feed + style + "<div style=\"text-align:center;\">" + "<img src=\"" + outputfile + "\" />" + "<p></p>" + "<img src=\"" + outputfile1 + "\" + style=\"width:400px;height:150px;" + "\" />" + "<p><h3 style=\"text-align:center;"+"\">" + "THIS IS TO CERTIFY" + "</h3></p>" + "<p><h3 style=\"text-align:center;"+"\">"+ user + "</h3></p>" + "<p>" + "</p>" + "<p>" + "<img src=\"" + outputfile2 + "\" />" + "</p>" + "<p>" + "</p>" + "<p><h3 style=\"text-align:center;"+"\">"+ dateTXT + " " + date + "</h3></p>" + "<p><h3 style=\"text-align:center;"+"\">" + "SIGNED" + "</h3></p>" + "<p>" + "</p>" + "<p>" + "<img src=\"" + outputfile3 + "\" + style=\"width:150px;height:150px;"+"\" />" + "</p>" + "<p>" + "</p>" + "<p>" + "<img src=\"" + outputfile4 + "\" />" + "</p>" + "<p></p>" + "<p></p>" + "</div>" + htmlend;
total = completehtml + named + completehtml1 + htmlend;
System.out.println("complete HTML" + completehtml);
System.out.println("STARTED!!!");
ByteArrayOutputStream baos1 = new ByteArrayOutputStream();
ObjectOutputStream file = new ObjectOutputStream(baos1);
Document document = new Document();
PdfWriter pdfwriter = PdfWriter.getInstance(document, baos1);
document.open();
System.out.println("DOCUMENT OPEN");
document.addAuthor("James Parish");
XMLWorkerHelper worker = XMLWorkerHelper.getInstance();
worker.parseXHtml(pdfwriter, document, new StringReader(completehtml));
// worker.parseXHtml(pdfwriter, document, new FileInputStream("Images/image001.jpg"));
System.out.println("NEW PARAGRAPH");
System.out.println("PARAGRAPH ADDED");
document.close();
System.out.println("CLOSED DOCUMENT!");
file.close();
System.out.println("CLOSED FILE");
System.out.println("pdf is" + file);
System.out.println("ENDED!!!");
Email from = new Email(msgfrom);
Email to = new Email(msgto);
Content content = new Content("text/plain", msgbody);
Mail mail = new Mail(from, subject, to, content);
ByteArrayOutputStream fileData = null;
byte[] testing = baos1.toByteArray();
try {
fileData = baos1;
Attachments attachments3 = new Attachments();
Base64 x = new Base64();
String imageDataString = Base64.encodeBase64String(testing);
attachments3.setContent(imageDataString);
attachments3.setType("application/pdf");//"application/pdf"
attachments3.setFilename("Certificate.pdf");
attachments3.setDisposition("attachment");
attachments3.setContentId("Banner");
mail.addAttachments(attachments3);
System.out.println("BASE64 ENCODED ATTACHMENT " + imageDataString);
I have my GWT project and I want to upload files to server. I want the following algorithm to work
1) create a folder with the name from "userNumber"
2) write uploaded files to this folder
3) add folder to zip
4) delete folder (if exists)
As I write on the server side I think it is just java problem. Here is my code. I can perform only the first and the second steps, i.e. I can create a folder and write files to this folder.
#Override
public String executeAction(HttpServletRequest request,
List<FileItem> sessionFiles) throws UploadActionException {
String response = "";
userNumber = request.getParameter("userNumber");
File f = new File(ConfAppServer.getRealContextPath() + "/edoc/"
+ userNumber);
if (f.mkdir()) {
System.out.println("Directory Created");
} else {
System.out.println("Directory is not created");
}
for (FileItem item : sessionFiles) {
if (false == item.isFormField()) {
try {
String extension = item.getName().substring(
item.getName().length() - 3);
File file = null;
file = new File(ConfAppServer.getRealContextPath()
+ "/edoc/"
+ userNumber
+ System.getProperty("file.separator")
+ item.getName().substring(0,
item.getName().length() - 4) + "."
+ extension);
item.write(file);
receivedFiles.put(item.getFieldName(), file);
receivedContentTypes.put(item.getFieldName(),
item.getContentType());
response += "<file-" + cont + "-field>"
+ item.getFieldName() + "</file-" + cont
+ "-field>\n";
response += "<file-" + cont + "-name>" + item.getName()
+ "</file-" + cont + "-name>\n";
response += "<file-" + cont + "-size>" + item.getSize()
+ "</file-" + cont + "-size>\n";
response += "<file-" + cont + "-type>"
+ item.getContentType() + "</file-" + cont
+ "type>\n";
} catch (Exception e) {
throw new UploadActionException(e);
}
}
}
ZipUtils appZip = new ZipUtils(userNumber + ".zip",
ConfAppServer.getRealContextPath() + "/edoc/" + userNumber);
appZip.generateFileList(new File(ConfAppServer.getRealContextPath()
+ "/edoc/" + userNumber));
appZip.zipIt(userNumber + ".zip");
f.delete();
removeSessionFileItems(request);
return "<response>\n" + response + "</response>\n";
}
Here you can find my ZipUtils class.
When I try to delete my folder, nothing happens. The delete() method doesn't work. Help me please!!
My question is how to add folder to zip and then delete this folder.
Use java.nio.file. You won't have the hassle of manipulating the ZIP API yourself:
final Path pathToZip = Paths.get("path", "to", "your", "zip");
final URI uri = URI.create("jar:" + pathToZip.toUri());
final Map<String, ?> env = Collections.singletonMap("create", "true");
try (
final FileSystem fs = FileSystems.getFileSystem(uri, env);
) {
// write files into the zip here.
// See javadoc for java.nio.file.Files and FileSystem.getPath()
}
More details on how to use the API here.
I'm storing images on S3 for use in emails. When I view the image in an email, some of the images are rotated. I'm uploading using the AmazonS3Client, and uploading images using MultipartFormData in a Play2 app like this:
Http.MultipartFormData body = request().body().asMultipartFormData();
String[] pics = new String[]{"picture1", "picture2", "picture3"};
String[] fileNames = new String[3];
for(int i = 0; i < pics.length; i++) {
Http.MultipartFormData.FilePart picture = body.getFile(pics[i]);
if (picture != null) {
String fileName = picture.getFilename();
play.Logger.info("fileName: " + fileName);
File file = picture.getFile();
String existingBucketName = "yadayadayada";
String keyName = UUID.randomUUID().toString();
PutObjectRequest putObjectRequest = new PutObjectRequest(existingBucketName, keyName + "-" + fileName, file);
putObjectRequest.withCannedAcl(CannedAccessControlList.PublicRead); // public for all
s3Client.putObject(putObjectRequest);
fileNames[i] = "https://s3.amazonaws.com/yadayadayada/" + keyName + "-" + fileName;
}
}
I was trying to move file using move file method .but getting this error
"java.io.IOException: Failed to delete original file"
this is my code.
this is for file move without error
public void moveWithoutError(String fileName){
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
String ts = dateFormat.format(date);
File source = new File("D:/Inbound/");
File dest = new File("D:/Archive/");
for (File file : source.listFiles()) {
String x = (source + "/" + file.getName());
String y = (dest + "/" + addTimestamp(file.getName(), ts));
if(file.getName().equals(fileName)){
File sourceFile = new File(x);
File destnFile = new File(y);
try{
FileUtils.moveFile(sourceFile, destnFile);
System.out.println("Moved file:"+y);
}catch(Exception e){
System.out.println("Unable to move file:"+y);
System.out.println(e);
e.printStackTrace();
}
break;
}
}
}
This code is written for moving the file with containing error
public void moveWithError(String fileName){
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
String ts = dateFormat.format(date);
File source = new File("D:/Inbound\\");
File dest = new File("D:\\Error\\"); /
for (File file : source.listFiles()) {
String x = (source + "/" + file.getName());
String y = (dest + "/" + addTimestamp(file.getName(), ts));
if(file.getName().equals(fileName)){
File f1 = new File(x);
if(f1.renameTo(new File(y))){
System.out.println(" moved: " + y);
} else {
System.out.println("unable to move: " + y);
}
break;
}
}
}
This code is used to add timestamp to moved file
public static String addTimestamp(String name, String ts) {
int lastIndexOf = name.lastIndexOf('.');
return (lastIndexOf == -1 ?
name + "_" + ts
:
name.substring(0, lastIndexOf) + "-" + ts +
name.substring(lastIndexOf))
.replaceAll("[\\/:\\*\\?\"<>| ]", "");
}
}
while executing this code exception come
abd exception is
"java.io.IOException: Failed to delete original file 'D:\Inbound\Testdata.xlsx' after copy to 'D:\Archive\Testdata-20140812121814.xlsx'"
Note - this file is nor open neither accessing by other process
Please help :(
Exception
java.io.IOException: Failed to delete original file 'D:\Inbound\Testdata.xlsx' after copy to 'D:\Archive\Testdata-20140812130655.xlsx'
at org.apache.commons.io.FileUtils.moveFile(FileUtils.java:2664)
at CRP.MoveFile.moveWithoutError (MoveFile.java:77)
at CRP.CRPDAO.callMoveFile (CRPDAO.java:562)
at CRP.CRP_FileDependency.main (CRP_FileDependency.java:163)