How to get svg in database injava - java

I am having 1 problem. I save SVG images in the database as binary. Now, I want to download it without converting to base64, is there any way. Thank you.

Basically, that would mean getting the BLOB object from the database.
I would follow this approach to show it in directly in the browser:
#RestController
public class ImageController {
#GetMapping(value = "/img-test", produces = "image/svg+xml")
public byte[] getImg() throws IOException
{
// retrieve your image from the DB
File imgFile = new File("C:\\Users\\USR\\Desktop\\img.svg");
InputStream inp = new DataInputStream(new FileInputStream(imgFile));
return inp.readAllBytes(); // This is a Java 9 specific convertion
}
}
With this approach, you do not change anything on the BLOB image. You take it and return it as is, an array with bytes. And you can directly show it in a browser or embed it somewhere in your HTML file.
The main thing here is the MIME type : image/svg+xml
If you are using an older version of Java, then check this question for the conversion of the InputStream object to a byte array.
And with this approach you can download the file:
#GetMapping("download-img")
public ResponseEntity downloadImg() throws IOException
{
// Get the file from the DB...
File imgFile = new File("C:\\Users\\USR\\Desktop\\img.svg");
InputStream inp = new DataInputStream(new FileInputStream(imgFile));
//Dynamically change the File Name here
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"img.svg\"")
.body(inp.readAllBytes());
}

Related

aspose convert pdf to excel as temporary file

The question is rather simple. I am using the aspose library to convert a pdf file to excel. The excel file is subsequently written to the database and this generated excel file is not needed in the future.
My method:
public void main(MultipartFile file) throws IOException {
InputStream inputStream = file.getInputStream();
Document document = new Document(inputStream);
ExcelSaveOptions options = new ExcelSaveOptions();
options.setFormat(ExcelSaveOptions.ExcelFormat.XLSX);
document.save("newExcelFile.xlsx", options);
}
In this method, the file is saved to the root folder of the project (if it is running locally). How can I not store this file, but make it temporary? My question is that this project is located on the server, and I would not like to create directories specifically for this file.
The Document.save() method has an overload for saving to an OutputStream (See here for the API reference).
Given that you can store the result to anything that implements an OutputStream, you can provide any implementation that you want - one useful option might be to use ByteArrayOutputStream to store the result in memory, or possibly - just use Files.createTempFile() and create a FileOutputStream for that.
For example, your code may be rewritten thus:
public byte[] convertToExcel(MultipartFile file) throws IOException {
InputStream inputStream = file.getInputStream();
Document document = new Document(inputStream);
ExcelSaveOptions options = new ExcelSaveOptions();
options.setFormat(ExcelSaveOptions.ExcelFormat.XLSX);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
document.save(baos, options);
return baos.toByteArray();
}

Input image not getting read in java with getResource

I'm trying to add image of user's selection to my pdf generated through pdfbox in netbeans. If i directly give path to directly then it's working but with getting url of image path and adding that doesn't work.
See the given code problem is with URL and Path, Because input isn't getting read
public static ByteArrayOutputStream PDFGenerator(........,Path imagespath)
{
........
if (finalpdf.Images != null)
{
Path imagepath = Paths.get(imagespath.toString(), "room.png");
PDImageXObject Addedimage = PDImageXObject.createFromFile(imagepath.toString(), pdf);
AddImages(content, Addedimage, 229.14f, 9.36f);
}
//AddImages method is following
public static void AddImages(PDPageContentStream content, PDImageXObject image, float x, float y) throws IOException
{
content.drawImage(image, x, y);
}
}
//Following is snippet from my test method
public void testClass()
{
........
finalpdf.Images = "room.png";
URL imageurl = testclass.class.getResource("room.png");
Path imagepath = Paths.get(imageurl.getPath().substring(1));
ByteArrayOutputStream baos = PDFGenerator.generatefurtherpdf(finalpdf, "0000.00", "00.00", imagepath);
writePDF(baos, "YourPdf.pdf");
}
I expect that it works this way but i'm sure its some problem with Path, I'm not using this correctly. I hope the code is explanatory enough as i'm quite new also there are security reasons so I can't put the whole code. Sorry for mistakes
For resources (never a File) there exists a generalized class: Path.
Path path = Paths.get(imageurl.toURI());
However whenever that path (for instance with an URL ´jar:file//... .jar!... ... .png") will be used as File, which an path.toString() suggests, one can use an InputStream.
The second generalized class is an InputStream which is more low-level:
InputStream in = TestClass.getResourceAsStream(imagepath);
This is a short-cut for the never used getResource().openStream(). Throwing a NullPointerException when the resource path is incorrect.
The last ressort is to use the actual byte[] for createFromByteArray.
byte[] bytes = Files.readAllBytes(path);
PDImageXObject Addedimage = PDImageXObject.createFromByteArray(doc, bytes, name);
Using a temporary file
Path imagepath2 = Files.createTempFile("room", ".png");
Files.copy(imagepath, imagepath2);
PDImageXObject Addedimage = PDImageXObject.createFromFile(imagepath2.toString(), pdf);

How to upload multiple files in Play Framework using Java

Hi i have been trying to upload image file in Play Framework. I have been trying out with Java File Upload since morning but unable to do so. I have seen [JavaFileUpload][1] tutorial available on framework website. But i am still not successful. Here is my code which i am trying to run:
Http.MultipartFormData body = request().body().asMultipartFormData();
List<Http.MultipartFormData.FilePart> fileParts = body.getFiles();
for (Http.MultipartFormData.FilePart filePart : fileParts) {
String filename = filePart.getFilename();
File file = filePart.getFile(); //error comes on this line
if (filePart.getFilename().toLowerCase().endsWith(".png")) {
//saving here but how?
} else {
return badRequest("Invalid request, only PNGs are allowed.");
}
}
but problem is that whenever i try to get the file i am having this conversion error:
java.lang.Object cannot be converted to java.io.File
Anyone can guide me in the direction? if we see the official document there is no proper documentation on how to upload multiple files. If anyone can show me some website which can helps me in that direction that will be also helpful
I'm using Play 2.4 and
FilePart filePart = request().body().asMultipartFormData()
.getFile("myFileKey");
File file = filePart.getFile();
With Play 2.2 I used for multiple file uploads:
MultipartFormData mfd = request().body().asMultipartFormData();
List<FilePart> filePartList = mfd.getFiles();
FilePart filePart = filePartList.get(0);
So after lots of trouble i was able to figure out the answer to my question. Here i am going to post the answer so it helps other people searching the answer to the same problem i faced
The controller function call which will upload the files looks like this:
Http.MultipartFormData body = request().body().asMultipartFormData();
List<Http.MultipartFormData.FilePart> fileParts = body.getFiles();
for (Http.MultipartFormData.FilePart filePart : fileParts) {
if (filePart.getFilename().toLowerCase().endsWith(".png")) {
String filename = filePart.getFilename();
Files.write(Paths.get(filename + ".png"), readContentIntoByteArray((File) filePart.getFile()));
} else {
return badRequest("Invalid request, only PNGs are allowed.");
}
}
I am using a function call to read the content of the file into byte array and save them inside the file:
private static byte[] readContentIntoByteArray(File file) {
FileInputStream fileInputStream = null;
byte[] bFile = new byte[(int) file.length()];
try {
//convert file into array of bytes
fileInputStream = new FileInputStream(file);
fileInputStream.read(bFile);
fileInputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
return bFile;
}
Remember you can choose whatever the path you want to save the file at Paths.get(filename + ".png")

Create and download CSV file in a Java servlet

I am working on Java ExtJS application in which I need to create and download a CSV file.
On clicking a button I want a CSV file to be downloaded to a client's
machine.
On buttons listener I am calling a servlet using AJAX. There I am
creating a CSV file.
I don't want the CSV file to be saved in the server. I want the file should be created dynamically with a download option. I want the contents of a file to be created as a string and then I will serve the content as file in which it will open as download mode in browser (this I have achieved in other language, but not sure how to achieve it in Java).
Here is my code only to create a CSV file, but I really don't want to create or save CSV file if I can only download the file as CSV.
public String createCSV() {
try {
String filename = "c:\\test.csv";
FileWriter fw = new FileWriter(filename);
fw.append("XXXX");
fw.append(',');
fw.append("YYYY");
fw.append(',');
fw.append("ZZZZ");
fw.append(',');
fw.append("AAAA");
fw.append(',');
fw.append("BBBB");
fw.append('\n');
CSVResult.close();
return "Csv file Successfully created";
} catch(Exception e) {
return e.toString();
}
}
Can any one help me on this.
Thanks
I got the solution and I am posting it below.
public void doGet(HttpServletRequest request, HttpServletResponse response)
{
response.setContentType("text/csv");
response.setHeader("Content-Disposition", "attachment; filename=\"userDirectory.csv\"");
try
{
OutputStream outputStream = response.getOutputStream();
String outputResult = "xxxx, yyyy, zzzz, aaaa, bbbb, ccccc, dddd, eeee, ffff, gggg\n";
outputStream.write(outputResult.getBytes());
outputStream.flush();
outputStream.close();
}
catch(Exception e)
{
System.out.println(e.toString());
}
}
Here we don't need to save / store the file in the server.
Thanks
First of all you need to get the HttpServletResponse object so that you can stream a file into it.
Note : This example is something I Wrote for one of my projects and it works.Works on Java 7.
Assuming you got the HttpServletResponse you can do something like this to stream a file. This way the file will be saved into clients' machine.
public void downloadFile(HttpServletResponse response){
String sourceFile = "c:\\source.csv";
try {
FileInputStream inputStream = new FileInputStream(sourceFile);
String disposition = "attachment; fileName=outputfile.csv";
response.setContentType("text/csv");
response.setHeader("Content-Disposition", disposition);
response.setHeader("content-Length", String.valueOf(stream(inputStream, response.getOutputStream())));
} catch (IOException e) {
logger.error("Error occurred while downloading file {}",e);
}
}
And the stream method should be like this.
private long stream(InputStream input, OutputStream output) throws IOException {
try (ReadableByteChannel inputChannel = Channels.newChannel(input); WritableByteChannel outputChannel = Channels.newChannel(output)) {
ByteBuffer buffer = ByteBuffer.allocate(10240);
long size = 0;
while (inputChannel.read(buffer) != -1) {
buffer.flip();
size += outputChannel.write(buffer);
buffer.clear();
}
return size;
}
}
What this does is, get an inputstream from your source file and write that stream into the outputstream of the HttpServletResponse. This should work since it works perfectly for me. Hope this helps. Sorry for my bad English.
I would like add something to the answer by gaurav. I recently had to implment this functionality in a project of mine and using javascript was out of the question becuase we had to support IE 9. What is the problem with IE 9?
(Export to CSV using jQuery and html), see the second answer in the link.
I needed an easy way to convert a ResultSet of a database query to a string which represent the the same data in CSV format. For that I used http://opencsv.sourceforge.net/ which provided an easy way to get a String ot of the ResultSet, and the rest is as above answer did it.
THe examples in the project soruce folder give good examples.

Convert PDF to Base64 and store data to BLOB of Database

I want to binary data (e.g. a PDF) into a BLOB of my Oracle database.
At first I putted the PDF into a FileInputStream and created a byte-array.Here is the code for that:
public static byte[] createByteArray(File pCurrentFolder, String pNameOfBinaryFile)
{
String pathToBinaryData = pCurrentFolder.getAbsolutePath()+"/"+pNameOfBinaryFile;
File file = new File(pathToBinaryData);
if (!file.exists())
{
System.out.println(pNameOfBinaryFile+" could not be found in folder "+pCurrentFolder.getName());
return null;
}
FileInputStream fin = null;
try {
fin = new FileInputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
byte fileContent[] = new byte[(int) file.length()];
try {
fin.read(fileContent);
} catch (IOException e) {
e.printStackTrace();
}
return fileContent;
}
I sent this (the byte array) via MyBatis to the database and it worked, so that I had the PDF in my BLOB and I also could read the PDF from my database.
But now I face the following problem:
I have a JDBC Connector for my search engine (FAST ESP...but that dowsnt matter) which connects to a certain database and stores all the content to a xml file. Inside this xml file is an element called "data" which contains the binary data inside its CDATA Field.
When I want to parse this xml, Java tells me:
The content of elements must consist of well-formed character data or markup.
With some PDF's i works but with some not. So I think the problem is, that I have stored them in the database in the wrong way.
For further information I would reverence to another questions I asked before which is similar to that.
Java: skip binary data in xml file while parsing
Someone there told me that I should encode my PDF (or any binary file) with base64. So that would mean, I do not just put my PDF into a FileInputStream, store the byte[] and put this byte[] to my BLOB of the database.
What do I have to do, to store the PDF in correct way inside my database, so that afterwards I can correctly parse my XML file the JDBC connector creates?
You can use the JAXB DatatypeConverter class to easily convert your data to base64 without any external dependencies:
byte[] arr = YOUR_BINARY_ARRAY;
String result = javax.xml.bind.DatatypeConverter.printBase64Binary(arr);
You can simply add this code to the end of your method and change its return type to a String.
You can try to first convert the bytes to basse64 using Apache Commons as this example:
import org.apache.commons.codec.binary.Base64;
import java.util.Arrays;
public class Base64Encode {
public static void main(String[] args) {
String hello = "Hello World";
byte[] encoded = Base64.encodeBase64(hello.getBytes());
System.out.println(Arrays.toString(encoded));
String encodedString = new String(encoded);
System.out.println(hello + " = " + encodedString);
}
}

Categories

Resources