NoOutputStreamException during image upload in vaadin - java

Trying to upload only images. The problem is that I don't know how to handle this situation.
#Override
public OutputStream receiveUpload(String filename, String mimeType) {
FileOutputStream fos = null;
if(mimeType.startsWith("image")) {
picture = new Picture();
picture.filename = filename;
picture.mimeType = mimeType;
picture = HibernateUtils.save(picture);
product.pictures.add(picture);
File dirs = new File(IMAGE_LOCATION);
File file = new File(IMAGE_LOCATION + picture.id);
if (!dirs.exists()) {
dirs.mkdirs();
}
try {
fos = new FileOutputStream(file);
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
} else {
Notification.show("", Notification.Type.ERROR_MESSAGE);
}
return fos;
}
The problem is that the fos variable will be null if I try to upload different type of files than image. The question is that, how should I handle it?

I'd do something like this:
...
} else {
Notification.show("", Notification.Type.ERROR_MESSAGE);
return new ByteArrayOutputStream();
}
...

Related

Copy file from path to Path in Android 11

I hope you are fine.
After I have done all steps, of getting permission storage in Android 11, now I can create, copy files from assets to any folder, or delete files.
I just got a problem when try to copy file from path to path, the problem is I find the output file empty.
Only in this I need help, and I hope you help me and tell me what mistake I have in my code, and thanks in advance.
To copy I'm using:
Uri muri = Uri.parse("content://com.android.externalstorage.documents/tree/primary%3Aagora%2file.txt");
Uri uri2 = Uri.parse("content://com.android.externalstorage.documents/tree/primary%3AAlarms");
DocumentFile mfile = DocumentFile.fromTreeUri(MainActivity.this, muri);
DocumentFile mfile1 = DocumentFile.fromTreeUri(MainActivity.this, uri2);
mfile1 = mfile1.createFile("file/txt", "file.txt");
uri2 = mfile1.getUri();
if (copyFileFromUri2(MainActivity.this, muri, uri2)) {
showMessage("file copied successfully");
} else {
showMessage("failed to copy the file !");
}
The method:
public boolean copyFileFromUri2(Context context, Uri fileUri, Uri targetUri)
{
InputStream fis = null;
OutputStream fos = null;
try {
ContentResolver content = context.getContentResolver();
fis = content.openInputStream(fileUri);
fos = content.openOutputStream(targetUri);
byte[] buff = new byte[1024];
int length = 0;
while ((length = fis.read(buff)) > 0) {
fos.write(buff, 0, length);
}
} catch (IOException e) {
return false;
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
return false;
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
return false;
}
}
}
return true;
}
You can try to initialize the OutputStream os as follows:
fos = new BufferedOutputStream( content.openOutputStream(targetUri))

Downloading images from AWS gives me corrupt files

I'm trying to download images that are hosted on Amazon Web Services. My methods work fine on any other host, but downloading an image off this url for example http://s3-eu-west-1.amazonaws.com/static.melkweg.nl/uploads/images/scaled/event_header/18226 is giving me trouble. It does download, but the file is only 49kb big and cannot be opened.
I've tried different methods such as Apache's FileUtils copyURLToFile, BufferedInputStream, ImageIO, etc. Some throw errors, most just download a corrupt file.
Here are the methods I've tried:
public static void downloadApache(String imageurl, String target)
{
try
{
File file = new File(target);
URL url = new URL(imageurl);
FileUtils.copyURLToFile(url, file);
}
catch(Exception e)
{
System.err.println("[3]Something went wrong.");
}
}
public static void downloadImage(String imageurl, String name)
{
try
{
URL url = new URL(imageurl);
InputStream in = new BufferedInputStream(url.openStream());
OutputStream out = new BufferedOutputStream(new FileOutputStream(name));
for ( int i; (i = in.read()) != -1; ) {
out.write(i);
}
in.close();
out.close();
}
catch(Exception e)
{
e.printStackTrace();
System.err.println("[0]Something went wrong.");
}
}
public static void downloadImageIO(String imageurl, String target)
{
try
{
URL url = new URL(imageurl);
BufferedImage image = ImageIO.read(url);
ImageIO.write(image, "jpg", new File(target));
}
catch(Exception e)
{
e.printStackTrace();
System.err.println("[1]Something went wrong.");
}
}
public static void downloadImageCopy(String imageurl, String target)
{
try
{
try (InputStream in = new URL(imageurl).openStream()) {
Files.copy(in, Paths.get(target), StandardCopyOption.REPLACE_EXISTING);
}
}
catch(Exception e)
{
e.printStackTrace();
System.err.println("[2]Something went wrong.");
}
}
And here's the main method if that is of any interest
public static void main(String[] args)
{
String imageurl = "http://s3-eu-west-1.amazonaws.com/static.melkweg.nl/uploads/images/scaled/event_header/18226";
String name = "downloaded_image.jpg";
String target = "C:/Users/Robotic/Downloads/" + name;
Download.downloadImage(imageurl, name);
Download.downloadImageCopy(imageurl, target);
Download.downloadImageIO(imageurl, target);
Download.downloadApache(imageurl, target);
}
Thanks in advance.
The file that you are getting from S3 is gzip compressed, you need to decompress it before trying to read it.
$ wget http://s3-eu-west-1.amazonaws.com/static.melkweg.nl/uploads/images/scaled/event_header/18226
$ file 18226
18226: gzip compressed data, from Unix
As pointed out in the earlier answer, it is in gzip format.
You can use the following method and get the file unzipped
public static void downloadApache(String imageurl, String target) {
try {
File file = new File(target+".gzip");
URL url = new URL(imageurl);
FileUtils.copyURLToFile(url, file);
byte[] buffer = new byte[1024];
try {
java.util.zip.GZIPInputStream gzis = new java.util.zip.GZIPInputStream(new FileInputStream(file));
FileOutputStream out = new FileOutputStream(target);
int len;
while ((len = gzis.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
gzis.close();
out.close();
} catch (IOException ex) {
ex.printStackTrace();
}
} catch (Exception e) {
System.err.println("[3]Something went wrong.");
}
}

How to let user download zip file using vaadin file downloader

I've followed this topic and it perfectly works. Here's the function to create resource for file downloader
private StreamResource createResource() {
return new StreamResource(new StreamSource() {
#Override
public InputStream getStream() {
String text = "My image";
BufferedImage bi = new BufferedImage(100, 30, BufferedImage.TYPE_3BYTE_BGR);
bi.getGraphics().drawChars(text.toCharArray(), 0, text.length(), 10, 20);
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ImageIO.write(bi, "png", bos);
return new ByteArrayInputStream(bos.toByteArray());
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}, "myImage.png");
}
but i don't know how to make it create a resource of zip file. Do i need to create many resources?. Thank you
Here's the solution that i figured out myself
private StreamResource createZipResource()
{
return new StreamResource(new StreamSource()
{
#Override
public InputStream getStream()
{
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
try
{
ZipOutputStream out = new ZipOutputStream(byteArrayOutputStream);
for (int i = 0; i < listData.size(); i++)
{
if (listData.get(i).contains(".txt"))
{
out.putNextEntry(new ZipEntry(listData.get(i) + ".txt"));
}
else
{
out.write(listData.get(i).getBytes());
}
}
out.close();
return new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
}
catch (IOException e)
{
System.out.println("Problem writing ZIP file: " + e);
}
return null;
}
},"Filename.zip");
}

Resolving the issue: Illegal characters in path

I am developing an application that takes an XML file and an attachment to be sent to the following path. This path is for a fax appliance.
I keep getting this error message:
Problem processing drop file "\co1-aux01prd01.tampa.healthe\Fax_Drop\Outbox\FaxDropSample1.xml": Illegal characters in path.
The XML file and the attachment are both being created but not processed.
public class TestSender {
public static void main(String[] args) {
String outBox = "\\\\faxaux\\Fax_Drop\\Outbox";
String filename = "FaxDrop" + ".xml";
String filepath = outBox + "\\" + filename;
Writer writer = null;
try {
BufferedImage image;
URL url = new URL("http://colsolgrp.com/phone/jpg/fax8.jpg");
image = ImageIO.read(url);
//File newImage = new File("\\\\faxaux\\Fax_Drop\\Outbox\\AttachmentFolder\\attachment.jpg");
File newImage = new File("\\\\faxaux\\Fax_Drop\\Outbox\\FaxDrop\\FaxDropImage.jpg");
newImage.mkdirs();
newImage.createNewFile();
ImageIO.write(image, "jpg",newImage);
System.out.println("File has been written");
}
catch(Exception e) {
System.out.println("Could not create file");
}
try {
File f = new File(filepath);
f.createNewFile();
FileOutputStream fileOutputStream = new FileOutputStream(f);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream);
writer = new BufferedWriter(outputStreamWriter);
// Create XML file here
}
catch (Throwable ex) {
ex.printStackTrace();
}
finally {
try {
writer.close();
}
catch (Exception ex) {
// Do nothing.
}
}
System.out.println("Success");
Try this:
URI u = new URI(URLEncoder.encode("\\co1-aux01prd01.tampa.healthe\Fax_Drop\Outbox\FaxDropSample1.xml"));

(how) can I download an image using JSoup?

I already know where the image is, but for simplicity's sake I wanted to download the image using JSoup itself. (This is to simplify getting cookies, referrer, etc.)
This is what I have so far:
//Open a URL Stream
Response resultImageResponse = Jsoup.connect(imageLocation).cookies(cookies).ignoreContentType(true).execute();
// output here
OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(new java.io.File(outputFolder + name));
//BufferedWriter out = new BufferedWriter(new FileWriter(outputFolder + name));
out.write(resultImageResponse.body()); // resultImageResponse.body() is where the image's contents are.
out.close();
I didn't even finish writing the question before I found the answer via JSoup and a little experimentation.
//Open a URL Stream
Response resultImageResponse = Jsoup.connect(imageLocation).cookies(cookies)
.ignoreContentType(true).execute();
// output here
FileOutputStream out = (new FileOutputStream(new java.io.File(outputFolder + name)));
out.write(resultImageResponse.bodyAsBytes()); // resultImageResponse.body() is where the image's contents are.
out.close();
Simply you can use these methods-
public static String storeImageIntoFS(String imageUrl, String fileName, String relativePath) {
String imagePath = null;
try {
byte[] bytes = Jsoup.connect(imageUrl).ignoreContentType(true).execute().bodyAsBytes();
ByteBuffer buffer = ByteBuffer.wrap(bytes);
String rootTargetDirectory = IMAGE_HOME + "/"+relativePath;
imagePath = rootTargetDirectory + "/"+fileName;
saveByteBufferImage(buffer, rootTargetDirectory, fileName);
} catch (IOException e) {
e.printStackTrace();
}
return imagePath;
}
public static void saveByteBufferImage(ByteBuffer imageDataBytes, String rootTargetDirectory, String savedFileName) {
String uploadInputFile = rootTargetDirectory + "/"+savedFileName;
File rootTargetDir = new File(rootTargetDirectory);
if (!rootTargetDir.exists()) {
boolean created = rootTargetDir.mkdirs();
if (!created) {
System.out.println("Error while creating directory for location- "+rootTargetDirectory);
}
}
String[] fileNameParts = savedFileName.split("\\.");
String format = fileNameParts[fileNameParts.length-1];
File file = new File(uploadInputFile);
BufferedImage bufferedImage;
InputStream in = new ByteArrayInputStream(imageDataBytes.array());
try {
bufferedImage = ImageIO.read(in);
ImageIO.write(bufferedImage, format, file);
} catch (IOException e) {
e.printStackTrace();
}
}

Categories

Resources