How to convert MultipartFile into byte stream - java

//Or any other solution to saving multipartfile into DB.
I tried with this way but getting error.
File fileOne = new File("file.getOrignalFileName");//what should be kept inside this method
byte[] bFile = new byte[(int) fileOne.length()];
try {
FileInputStream fileInputStream = new FileInputStream(fileOne);
//convert file into array of bytes
fileInputStream.read(bFile);
fileInputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
questionDao.saveImage(bFile);

MultipartFile file;
byte [] byteArr=file.getBytes();
InputStream inputStream = new ByteArrayInputStream(byteArr);

//Start Photo Upload with Adhaar No//
if (simpleLoanDto.getPic() != null && simpleLoanDto.getAdharNo() != null) {
String ServerDirPath = globalVeriables.getAPath() + "\\";
File ServerDir = new File(ServerDirPath);
if (!ServerDir.exists()) {
ServerDir.mkdirs();
}
// Giving File operation permission for LINUX//
IOperation.setFileFolderPermission(ServerDirPath);
MultipartFile originalPic = simpleLoanDto.getPic();
byte[] ImageInByte = originalPic.getBytes();
FileOutputStream fosFor = new FileOutputStream(
new File(ServerDirPath + "\\" + simpleLoanDto.getAdharNo() + "_"+simpleLoanDto.getApplicantName()+"_.jpg"));
fosFor.write(ImageInByte);
fosFor.close();
}
//End Photo Upload with Adhaar No//

Related

Convert byte[] to PDF file without saving in local disk in Java

I am taking byte array as input and it should convert to PDF type file without writing into local system and this is my code:
public File convertToFile(byte[] data) throws IOException, NullPointerException {
FileOutputStream bar = null;
String pathname = "filename.pdf";
File file = new File(pathname);
try (ByteArrayInputStream bais = new ByteArrayInputStream(data);
ByteArrayOutputStream baos = new ByteArrayOutputStream(data.length)) {
bar = new FileOutputStream(file);
int c = 0;
while (c < bais.read()) {
baos.write(data);
baos.writeTo(bar);``
baos.flush();
}
} catch (Exception e) {
e.getMessage();
}
return file;
}
When I run this code it is returning my local path.

Creating a download for zip file containing text/csv from string variables

I currently need to create a zip file for downloading. This should contain two (2) csv files that are to be created from string variables. I'm at a loss on how I should do this. My draft is below.
public #ResponseBody Object getFileV1(HttpServletRequest request, HttpServletResponse response) {
try {
response.setContentType("application/zip");
response.setHeader("Content-Disposition", "attachment; filename=Reassigned Tickets Report " + new Date().toString() + ".zip");
String stringValue1 = "This is a test value for csv1";
String stringValue2 = "This is a test value for csv2";
InputStream is1 = new ByteArrayInputStream(stringValue1.getBytes("UTF-8"));
InputStream is2 = new ByteArrayInputStream(stringValue2.getBytes("UTF-8"));
ZipInputStream zin;
ZipEntry entry;
ZipOutputStream zout= new ZipOutputStream(response.getOutputStream());
zin = new ZipInputStream(is1);
entry = zin.getNextEntry();
zout.putNextEntry(entry);
zin = new ZipInputStream(is2);
entry = zin.getNextEntry();
zout.putNextEntry(entry);
zout.closeEntry();
zin.close();
zout.close();
response.flushBuffer();
return null;
} catch (Exception e) {
e.printStackTrace();
return e;
}
}
Obviously this is not working. Probably because I'm still a novice at this. Please bear with me.
I get a "java.lang.NullPointerException" at the line where "zout.putNextEntry" is called. Would appreciate your advice. Thank you in advance.
I solved my problem after a day of looking around. This works for me. But I'm not sure if this is the most efficient way.
public #ResponseBody Object getFileV1(HttpServletRequest request, HttpServletResponse response) {
try {
response.setContentType("application/zip");
response.setHeader("Content-Disposition", "attachment; filename=Test Report " + new Date().toString() + ".zip");
String stringValue1 = "This is a test value for csv1";
String stringValue2 = "This is a test value for csv2";
PrintWriter writer1 = new PrintWriter(new OutputStreamWriter(new FileOutputStream("stringValue1.csv"), "UTF-8"));
writer1.print(stringValue1);
writer1.close();
PrintWriter writer2 = new PrintWriter(new OutputStreamWriter(new FileOutputStream("stringValue2.csv"), "UTF-8"));
writer2.print(stringValue2);
writer2.close();
File file1 = new File("stringValue1.csv");
File file2 = new File("stringValue2.csv");
filesToZip(response, file1, file2);
file1.delete();
file2.delete();
response.flushBuffer();
return null;
} catch (Exception e) {
e.printStackTrace();
return e;
}
}
This is the method I got from another thread with a few edits.
public static void filesToZip(HttpServletResponse response, File... files) throws IOException {
// Create a buffer for reading the files
byte[] buf = new byte[1024];
// create the ZIP file
ZipOutputStream out = new ZipOutputStream(response.getOutputStream());
// compress the files
for(int i=0; i<files.length; i++) {
FileInputStream in = new FileInputStream(files[i].getName());
// add ZIP entry to output stream
out.putNextEntry(new ZipEntry(files[i].getName()));
// transfer bytes from the file to the ZIP file
int len;
while((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
// complete the entry
out.closeEntry();
in.close();
}
// complete the ZIP file
out.close();
}
The only thing I don't love is that I had to create temporary files and delete them after processing.

Download dynamically created zip files in play framework

Hi i am trying to write a play framework service where i can download multiple files. I create zip of multiple file on the fly but i am not sure how to send it as a response in Play Framework i will show what i have done so far.
public Result download() {
String[] items = request().queryString().get("items[]");
String toFilename = request().getQueryString("toFilename");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(baos))) {
for (String item : items) {
Path path = Paths.get(REPOSITORY_BASE_PATH, item);
if (Files.exists(path)) {
ZipEntry zipEntry = new ZipEntry(path.getFileName().toString());
zos.putNextEntry(zipEntry);
byte buffer[] = new byte[2048];
try (BufferedInputStream bis = new BufferedInputStream(Files.newInputStream(path))) {
int bytesRead = 0;
while ((bytesRead = bis.read(buffer)) != -1) {
zos.write(buffer, 0, bytesRead);
}
} finally {
zos.closeEntry();
}
}
}
response().setHeader("Content-Type", "application/zip");
response().setHeader("Content-Disposition", "inline; filename=\"" + MimeUtility.encodeWord(toFilename) + "\"");
//I am confused here how to output the response of zip file i have created
//I tried with the `baos` and with `zos` streams but not working
return ok(baos.toByteArray());
} catch (IOException e) {
LOG.error("copy:" + e.getMessage(), e);
return ok(error(e.getMessage()).toJSONString());
}
return null;
}
i tried sending response with return ok(baos.toByteArray()); i was able to download file but when i open the downloaded file it give me error An error occurred while loading the archive.
You need to close the zip file. After adding all entries, do: zos.close()
On a side note, I would recommend writing the zip file to disk rather than keeping it in a memory buffer. You could then use return ok(File content, String filename) to send its content to the client.
I am adding this answer if someone wants to know what was the final code:
String[] items = request().queryString().get("items[]");
String toFilename = request().getQueryString("toFilename");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(baos))) {
for (String item : items) {
Path path = Paths.get(REPOSITORY_BASE_PATH, item);
if (Files.exists(path)) {
ZipEntry zipEntry = new ZipEntry(path.getFileName().toString());
zos.putNextEntry(zipEntry);
byte buffer[] = new byte[2048];
try (BufferedInputStream bis = new BufferedInputStream(Files.newInputStream(path))) {
int bytesRead = 0;
while ((bytesRead = bis.read(buffer)) != -1) {
zos.write(buffer, 0, bytesRead);
}
} finally {
zos.closeEntry();
}
}
}
zos.close(); //closing the Zip
response().setHeader("Content-Type", "application/zip");
response().setHeader("Content-Disposition", "attachment; filename=\"" + MimeUtility.encodeWord(toFilename) + "\"");
return ok(baos.toByteArray());
} catch (IOException e) {
LOG.error("copy:" + e.getMessage(), e);
return ok(error(e.getMessage()).toJSONString());
}
Thank you for the help! There are two extra changes I made so it works for me in scala playframework 2.5.x
instead of return ok(baos.toByteArray()) ,
use Ok.chunked(StreamConverters.fromInputStream(fileByteData))
Instead of reading byte to byte the file,FileUtils.readFileToByteArray(file) can be very helpful here.
Attached is the complete version of my code.
import java.io.{BufferedOutputStream, ByteArrayInputStream, ByteArrayOutputStream}
import java.util.zip.{ZipEntry, ZipOutputStream}
import akka.stream.scaladsl.{StreamConverters}
import org.apache.commons.io.FileUtils
import play.api.mvc.{Action, Controller}
class HomeController extends Controller {
def single() = Action {
Ok.sendFile(
content = new java.io.File("C:\\Users\\a.csv"),
fileName = _ => "a.csv"
)
}
def zip() = Action {
Ok.chunked(StreamConverters.fromInputStream(fileByteData)).withHeaders(
CONTENT_TYPE -> "application/zip",
CONTENT_DISPOSITION -> s"attachment; filename = test.zip"
)
}
def fileByteData(): ByteArrayInputStream = {
val fileList = List(
new java.io.File("C:\\Users\\a.csv"),
new java.io.File("C:\\Users\\b.csv")
)
val baos = new ByteArrayOutputStream()
val zos = new ZipOutputStream(new BufferedOutputStream(baos))
try {
fileList.map(file => {
zos.putNextEntry(new ZipEntry(file.toPath.getFileName.toString))
zos.write(FileUtils.readFileToByteArray(file))
zos.closeEntry()
})
} finally {
zos.close()
}
new ByteArrayInputStream(baos.toByteArray)
}
}

Not in GZIP Format - JAVA

I'm trying to write compressed data to a file and then read in the data and decompress it using the GZIP library. I've tried changing all formatting to StandardCharsets.UTF-8 and ISO-8859-1 and neither have fixed the GZIP format error. I'm wondering if it could possible have to do with the file I'm reading in? Here's the compression function:
public static byte[] compress(String originalFile, String compressFile) throws IOException {
// read in data from text file
// The name of the file to open.
String fileName = originalFile;
// This will reference one line at a time
String line = null;
String original = "";
try {
// FileReader reads text files in the default encoding.
FileReader fileReader =
new FileReader(fileName);
// Always wrap FileReader in BufferedReader.
BufferedReader bufferedReader =
new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null) {
original.concat(line);
}
// Always close files.
bufferedReader.close();
}
catch(FileNotFoundException ex) {
System.out.println(
"Unable to open file '" +
fileName + "'");
}
catch(IOException ex) {
System.out.println(
"Error reading file '"
+ fileName + "'");
// Or we could just do this:
// ex.printStackTrace();
}
// create a new output stream for original string
try (ByteArrayOutputStream out = new ByteArrayOutputStream())
{
try (GZIPOutputStream gzip = new GZIPOutputStream(out))
{
gzip.write(original.getBytes(StandardCharsets.UTF_8));
}
byte[] compressed = out.toByteArray();
out.close();
String compressedFileName = compressFile;
try {
// Assume default encoding.
FileWriter fileWriter =
new FileWriter(compressedFileName);
// Always wrap FileWriter in BufferedWriter.
BufferedWriter bufferedWriter =
new BufferedWriter(fileWriter);
// Note that write() does not automatically
// append a newline character.
String compressedStr = compressed.toString();
bufferedWriter.write(compressedStr);
// Always close files.
bufferedWriter.close();
}
catch(IOException ex) {
System.out.println(
"Error writing to file '"
+ fileName + "'");
// Or we could just do this:
// ex.printStackTrace();
}
return compressed;
}
}
(I'm receiving the error on the line in the following decompression function) -
GZIPInputStream compressedByteArrayStream = new GZIPInputStream(new ByteArrayInputStream(s.getBytes(StandardCharsets.UTF_8)));
Decompression Function:
public static String decompress(String file) throws IOException {
byte[] compressed = {};
String s = "";
File fileName = new File(file);
FileInputStream fin = null;
try {
// create FileInputStream object
fin = new FileInputStream(fileName);
// Reads up to certain bytes of data from this input stream into an array of bytes.
fin.read(compressed);
//create string from byte array
s = new String(compressed);
System.out.println("File content: " + s);
}
catch (FileNotFoundException e) {
System.out.println("File not found" + e);
}
catch (IOException ioe) {
System.out.println("Exception while reading file " + ioe);
}
finally {
// close the streams using close method
try {
if (fin != null) {
fin.close();
}
}
catch (IOException ioe) {
System.out.println("Error while closing stream: " + ioe);
}
}
// create a new input string for compressed byte array
GZIPInputStream compressedByteArrayStream = new GZIPInputStream(new ByteArrayInputStream(s.getBytes(StandardCharsets.UTF_8)));
ByteArrayOutputStream byteOutput = new ByteArrayOutputStream();
byte[] buffer = new byte[8192];
// create a string builder and byte reader for the compressed byte array
BufferedReader decompressionBr = new BufferedReader(new InputStreamReader(compressedByteArrayStream, StandardCharsets.UTF_8));
StringBuilder decompressionSb = new StringBuilder();
// write data to decompressed string
String line1;
while((line1 = decompressionBr.readLine()) != null) {
decompressionSb.append(line1);
}
decompressionBr.close();
int len;
String uncompressedStr = "";
while((len = compressedByteArrayStream.read(buffer)) > 0) {
uncompressedStr = byteOutput.toString();
}
compressedByteArrayStream.close();
return uncompressedStr;
}
Here's the error message that i am receiving:
[B#7852e922
File content:
java.io.EOFException
at java.util.zip.GZIPInputStream.readUByte(GZIPInputStream.java:268)
at java.util.zip.GZIPInputStream.readUShort(GZIPInputStream.java:258)
at java.util.zip.GZIPInputStream.readHeader(GZIPInputStream.java:164)
at java.util.zip.GZIPInputStream.<init>(GZIPInputStream.java:79)
at java.util.zip.GZIPInputStream.<init>(GZIPInputStream.java:91)
at org.kingswoodoxford.Compression.decompress(Compression.java:136)
at org.kingswoodoxford.Compression.main(Compression.java:183)
Any suggestions as to how I might be able to fix this?
When you read the file you discard the new line at the end of each line.
A more efficient option which does do this is to copy a block i.e. char[] at a time. You can also convert the text as you go rather than creating a String or a byte[].
BTW original.concat(line); returns the concatenated string which you are discarding.
The real problem is you write to one stream and close a different one. This means that if there is any buffered data at the end of the file (and this is highly likely) the end of the file will be truncated and when you read it it will complain that your file is incomplete or EOFException.
Here is a shorter example
public static void compress(String originalFile, String compressFile) throws IOException {
char[] buffer = new char[8192];
try (
FileReader reader = new FileReader(originalFile);
Writer writer = new OutputStreamWriter(
new GZIPOutputStream(new FileOutputStream(compressFile)));
) {
for (int len; (len = reader.read(buffer)) > 0; )
writer.write(buffer, 0, len);
}
}
In the decompress, don't encode binary as text and attempt to get back the same data. It will almost certainly be corrupted. Try to use a buffer and a loop like I did for compress. i.e. it shouldn't be any more complicated.

Incorrect path to file

I don't know why but outStream = new FileOutputStream(file) and inStream = new FileInputStream(new File(file1.getName())) throw an exception. I have no idea what to do.
Here's some code of this:
File tempf = new File(cmds[1]); //cmds is a String with filename cmds[1] and pathname cmds[2] where to move the file
File tempw = new File(cmds[2]);
if(!tempf.isAbsolute() || !tempw.isAbsolute()){//here i make paths absolute
tempf = new File(tempf.getAbsolutePath());
tempw = new File(tempw.getAbsolutePath());
}
String from = cmds[1];
String where = cmds[2];
File file1 = tempf;
File file2 = new File (tempw.toString() + "/" + new File(cmds[1]).getName());
InputStream inStream = null;
OutputStream outStream = null;
try {
inStream = new FileInputStream(new File(file1.getName())); //throws an exception
outStream = new FileOutputStream(file2); //throws an exception too
byte[] buffer = new byte[16384];
int length;
while ((length = inStream.read(buffer)) > 0) {
outStream.write(buffer, 0, length);
}
if (inStream != null)
inStream.close();
if (outStream != null)
outStream.close();
file1.delete();
} catch (IOException e) {
System.err.println("permission denied");
}
} else {
System.err.println("incorrect syntax");
}
continue;
}
Looks like everything should work fine but it doesn't. I am getting
java.io.FileNotFoundException: C:\Users\Maxim\IdeaProjects\Testing\OneDrive\1234.txt
But as I see it's wrong path. Real path is C:\Users\Maxim\OneDrive
UPD! It's found out that the problem is that getAbsolutePath() returns a path where the project is, but it's not the path I need. I need C:\Users\Maxim\OneDrive BUT it returns C:\Users\Maxim\IdeaProjects\Testing\OneDrive BUT! .../Testng doesn't have OneDrive!
The constructors for FileInputStream and FileOutputStream throw errors if there is a problem accessing the file, like if it doesn't exist. To stop it from throwing a FileNotFoundException, make sure you create the file before instantiating a FileInput/OutputStream object.
try{
FileInputStream fis = new FileInputStream(file);
}catch(FileNotFoundException e){
e.printStackTrace();
}
Look at the documentation here.

Categories