Download excel file with vue and spring - java

I'm trying to make an excel file with spring (Java) and then send it to Vue, so I can download the file with the web browser.
I made the excel file with a service in Java, but I don't know how and what I have to return to Vue.
#RequestMapping(value = "/getmathresume", method = RequestMethod.GET)
public FileOutputStream getMathResume()
{
//Long code with XSSFWorkbook();
//.
//.
//.
// Finally I Write the output to a file, but I don't want to save it locally, instead, the idea
// is send it to Front and download the file with the Browser.
try {
FileOutputStream fileOut = new FileOutputStream("poi-generated-file.xlsx");
workbook.write(fileOut);
fileOut.close();
workbook.close();
}catch (FileNotFoundException e) {
System.out.println(e);
} catch (IOException e) {
e.printStackTrace();
}
//Using the code from the accepted answer
try {
File file = new File("poi-generated-file.xlsx");
Files.copy(file.toPath(), response.getOutputStream());
String mimeType = URLConnection.guessContentTypeFromName(file.getName());
String contentDisposition = String.format("attachment; filename=%s", file.getName());
int fileSize = Long.valueOf(file.length()).intValue();
response.setContentType(mimeType);
response.setHeader("Content-Disposition", contentDisposition);
response.setContentLength(fileSize);
}catch (FileNotFoundException e) {
System.out.println(e);
} catch (IOException e) {
e.printStackTrace();
}
}
__________________________VUE CODE____________________________
getMathResume()
{
axios({
url: 'http://localhost:8081/user/getmathresume',
method: 'GET',
responseType: 'blob',
}).then((response) => {
var fileURL = window.URL.createObjectURL(new Blob([response.data]));
var fileLink = document.createElement('a');
fileLink.href = fileURL;
fileLink.setAttribute('download', 'matematica.xlsx');
document.body.appendChild(fileLink);
fileLink.click();
});
},
I don't think this is a hard thing to do, but I cannot find a tutorial to do something like this.
Hope someone can help me out.
EDIT: ADDED THE NEW CODE WORKING.

#RequestMapping(value = "/getmathresume", method = RequestMethod.GET)
public void getMathResume(HttpServletResponse response) {
try {
File file = new File("poi-generated-file.xlsx");
Files.copy(file.toPath(), response.getOutputStream());
String mimeType = URLConnection.guessContentTypeFromName(file.getName());
String contentDisposition = String.format("attachment; filename=%s", file.getName());
int fileSize = Long.valueOf(file.length()).intValue();
response.setContentType(mimeType);
response.setHeader("Content-Disposition", contentDisposition);
response.setContentLength(fileSize);
}catch (FileNotFoundException e) {
System.out.println(e);
} catch (IOException e) {
e.printStackTrace();
}
}

Related

java download a file sourced from a database to PC

I am getting an image (jpeg or pdf) from a database and want to download it to the PC. However, the image is not recognised at !file.exists(). This points to File file = new File(resourceDetail.getResourseImage()); being incorrect. What is the correct way to code this please?
Note: resourceDetail.getResourseImage() is the actual image not a path.
My code is:
resourceDetail = MySQLConnection.resourceDownload(fileID);
FileInputStream stream = null;
try {
File file = new File(resourceDetail.getResourseImage());
System.out.println("resourceDetail.getResourseImage(): " + resourceDetail.getResourseImage());
if (!file.exists()) {
System.out.println("File does not exist: ");
// context.addMessage(new ErrorMessage("msg.file.notdownloaded"));
// context.setForwardName("failure");
} else {
System.out.println("File exist: ");
if (resourceDetail.getResourseImageType().equals("pdf")){
System.out.println("pdf: ");
response.setContentType("application/pdf");
response.setHeader("Content-Disposition", "attachment; filename='myfile.pdf'");
}else{
System.out.println("jpeg: ");
response.setContentType("image/jpeg");
response.setHeader("Content-Disposition", "attachment; filename='myfile.jpg'");
}
// response.setHeader("Content-Disposition", "attachment; filename=" + file.getName());
System.out.println("stream: ");
stream = new FileInputStream(file);
response.setContentLength(stream.available());
OutputStream os = response.getOutputStream();
os.close();
response.flushBuffer();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
resourceDetail.getResourseImage() got string data, you can directly write the data to response by using: OuputStream#write(bytes). In you case, just use ·os.write(resourceDetail.getResourseImage().getByets());` to do this.
The Sample code:
resourceDetail = MySQLConnection.resourceDownload(fileID);
try {
System.out.println(
"resourceDetail.getResourseImage(): " + resourceDetail.getResourseImage());
if (resourceDetail.getResourseImageType().equals("pdf")) {
System.out.println("pdf: ");
response.setContentType("application/pdf");
response.setHeader("Content-Disposition", "attachment; filename='myfile.pdf'");
} else {
System.out.println("jpeg: ");
response.setContentType("image/jpeg");
response.setHeader("Content-Disposition", "attachment; filename='myfile.jpg'");
}
response.setContentLength(resourceDetail.getResourseImage().length());
OutputStream os = response.getOutputStream();
os.write(resourceDetail.getResourseImage().getBytes());
os.close();
response.flushBuffer();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
While this solution does not directly answer the issue with java it does give me a solution. I started with using jQuery which worked with Chrome and not IE. I was told it was not possible to active downloading images with jQuery and that I needed to do it via java. However, I have now found:
http://danml.com/download.html
Kind regards,
Glyn

Error when connecting to FTP using apache commons

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();
}
}

Android: Saving .png from URL into app internal storage

I'm relatively new to android, and I'm trying to modify an android app such that it downloads a profile picture (preferably in PNG) from a URL, and saves it in the com.companyName.AppName.whatever/files. It should be noted that the app was initially created in Unity, and just built and exported.
Here's my initial code:
URL url = null;
try {
url = new URL(playerDO.getProfileURL());
} catch (MalformedURLException e) {
e.printStackTrace();
}
InputStream input = null;
try {
input = url.openStream();
} catch (IOException e) {
e.printStackTrace();
}
String fileName = playerDO.getId() + ".png";
FileOutputStream outputStream = null;
try {
outputStream = openFileOutput(fileName, Context.MODE_PRIVATE);
byte[] buffer = new byte[256];
int bytesRead = 0;
while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) {
outputStream.write(buffer, 0, bytesRead);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
outputStream.close();
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
EDIT: Here's my other code, as suggested by #Ashutosh Sagar
InputStream input = null;
Bitmap image = null;
try {
input = url.openStream();
image = BitmapFactory.decodeStream(input);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
String fileName = playerDO.getId() + ".png";
FileOutputStream outputStream = null;
File myDir = getFilesDir();
try {
Log.wtf("DIRECTORY", myDir.toString());
File imageFile = new File(myDir, fileName);
if (!imageFile.exists()){
imageFile.createNewFile();
Log.wtf("ANDROID NATIVE MSG: WARN!", "File does not exist. Writing to: " + imageFile.toString());
}
outputStream = new FileOutputStream(imageFile, false);
image.compress(Bitmap.CompressFormat.PNG, 90, outputStream);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
outputStream.close();
input.close();
} catch (IOException e) {
e.printStackTrace();
Log.wtf("AWWW CRAP", e.toString());
}
}
(It doesn't write either).
Unfortunately, I've had several problems with this. My primary issue is that when it (on the cases that it does) runs, it actually doesn't save anything. I'll go and check com.companyName.AppName.whatever/files directory only to find no such .png file. I will also need it to overwrite any existing files of the same name, which is hard to check when it doesn't work.
My secondary issue is that it fails to take into account delays in internet connection. Although I've put in enough try-catch clauses to stop it from crashing (as it used to), the end result is that it also doesn't save.
How can I improve upon this? Anything I'm missing?
EDIT:
Printing out the directory reveals it should be in:
/data/user/0/com.appName/files/5965e9e4a0f0463853016e2b.png
However, using ES File explorer, the only thing remotely close to that is
emulated/0/Android/data/com.appName/files/
Are they the same directory?
try this first get bitmap image from url
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(url).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.d("Error", e.getStackTrace().toString());
}
and to save bitmap image please check the ans of GoCrazy
Try this
void getImage(String string_url)
{
//Generate Bitmap from URL
URL url_value = new URL(string_url);
Bitmap image =
BitmapFactory.decodeStream(url_value.openConnection().getInputStream());
//Export File to local Directory
OutputStream stream = new FileOutputStream("path/file_name.png");
/* Write bitmap to file using JPEG or PNG and 80% quality hint for JPEG. */
bitmap.compress(CompressFormat.PNG, 80, stream);
stream.close();
}

Spring MVC - Create a ZIP file in memory and let user download

I have a web project that
pulls data from Oracle DB
creates an XML file out of that data using a HashMap
ZIP it in memory
let users download the ZIP file.
note that I will not create a physical file prior to download.
I am done with 1-3. I can't seem to find a solution for the download part. I am using pure Spring MVC (as much as I can), Hibernate, MySQL.
HomeController.java
#RequestMapping(value="/doretrieve", method=RequestMethod.POST, produces="application/zip")
#ResponseBody
public ZipOutputStream doRetrieve(#RequestParam(value="calcgrouplist") String selectedCalcGroups, #RequestParam(value="env") String currentEnv){
ZipOutputStream zipCalgGroups = null;
try {
String[] cgs = calcGroupService.insertToArray(selectedCalcGroups);
for(String cg:cgs){
System.out.println("Calculation Group: " + cg);
}
Map startRetrieve = calcGroupService.startRetrieve(currentEnv, cgs);
if (startRetrieve != null ){
zipCalgGroups = calcGroupService.zipCalcGroups(currentEnv, startRetrieve);
} else {
return null;
}
} catch (NullPointerException e) {
e.printStackTrace();
}
return zipCalgGroups;
}
CalcGroupService.java
code to create zip file of the xml file/s
public ZipOutputStream zipCalcGroups(String database, Map startRetrieve) {
//Sort
//SortCalcGroupParameters sort = new SortCalcGroupParameters();
//sort.run(new File("\\" + database));
Map<String, byte[]> mapXmlFiles = startRetrieve;
try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
ZipOutputStream zos = new ZipOutputStream(baos))
{
for (Map.Entry<String, byte[]> mapXmlFile:mapXmlFiles.entrySet()){
ZipEntry entry = new ZipEntry(mapXmlFile.getKey());
zos.putNextEntry(entry);
zos.write(mapXmlFile.getValue());
zos.closeEntry();
}
return zos;
} catch (IOException e) {
e.printStackTrace();
}
return null;
I was able to solve my own problem. Below are the edited methods:
HomeController:
#RequestMapping(value="/doretrieve", method=RequestMethod.POST, produces="application/zip")
#ResponseBody
public byte[] doRetrieve(HttpServletResponse response, #RequestParam(value="calcgrouplist")
String selectedCalcGroups, #RequestParam(value="env") String currentEnv){
try {
String[] cgs = calcGroupService.insertToArray(selectedCalcGroups);
for(String cg:cgs){
System.out.println("Calculation Group: " + cg);
}
//returns map of file name and xml
Map startRetrieve = calcGroupService.startRetrieve(currentEnv, cgs);
//set file name of the zipped calc group/s using selected environment
response.setHeader("Content-Disposition", "attachment; filename=" + currentEnv + ".zip");
if (startRetrieve != null ){
byte[] zipped = calcGroupService.zipCalcGroupsFromMemory(currentEnv, startRetrieve);
return zipped;
} else {
return null;
}
} catch (NullPointerException e) {
e.printStackTrace();
}
return null;
}
CalcGroupService:
public byte[] zipCalcGroupsFromMemory(String database, Map startRetrieve) {
Map<String, byte[]> mapXmlFiles = startRetrieve;
HttpServletRequest request = null;
try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
ZipOutputStream zos = new ZipOutputStream(baos)) {
for (Map.Entry<String, byte[]> mapXmlFile : mapXmlFiles.entrySet()) {
byte[] xml = sortCalcGroup(mapXmlFile.getKey(), mapXmlFile.getValue());
zos.putNextEntry(new ZipEntry(mapXmlFile.getKey()));
//zos.write(mapXmlFile.getValue());
zos.write(xml);
zos.closeEntry();
}
zos.close();
return baos.toByteArray();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
The above code produces a nice zipped xml file/s.

Download File in Java Spring rest api

I want to download a file and for that I have written this code:
public void downoadResume(#PathVariable("id") int id, HttpServletResponse response) {
try {
Applicant applicant = applicantService.getOne(id);
File file = new File(DocumentConstants.DOCUMENTS_PATH + "/" + applicant.getOriginalDocPath());
// get your file as InputStream
InputStreamReader is = new InputStreamReader(new FileInputStream(file.getAbsolutePath()));
// copy it to response's OutputStream
org.apache.commons.io.IOUtils.copy(is, response.getOutputStream());
is.close();
response.flushBuffer();
} catch (IOException ex) {
ex.printStackTrace();
} catch (ResourceNotFoundException e) {
e.printStackTrace();
}
}
But I am getting this kind of response instead of file, please check:
PK!�?�*��[Content_Types].xml �(���Oo�#��H|k���i�8=��X*���8Y���3i�o��I�RLHs���罟��3��g��G�hc��e5?
�Z|�ߕE?��Q.��P\�޿��7 ��ꀵX�OR�^?WX�?O���"��K����� �&�R�#��VC̦��QkG��3��%��P7�[�Z���Պ�T>�ʥ�9T\�݃+���1�thO�n�����dk�xP���g���&���g��pƦ���V-���3���O��a�?ġ�H���NZ�?c�˓qz�V2Y�3b��k����'��F/}(�i�ߞ`�{��wK�ۦ�]?����Z��w"���߿�r��p�<����g�x!>
��H!�9�}/=
���a�<��𬜫��#:����� ^ ���gQ'sȒGe7�x���x���h�K��G̻ޑ���9C���o٭��/��PK!���N_rels/.rels �(����JA���a�}7�
"���H�w"����w̤ھ�� �P�^����O֛���;�<�aYՠ؛`G�kxm��PY�[��g
Gΰino�/<���<�1��ⳆA$>"f3��\�ȾT�?I S?���������W����Y
ig�#��X6_�]7~
f��ˉ�ao�.b*lI�r?j)�,l0�%?�b�
6�i���D�_���, � ���|u�Z^t٢yǯ;!Y,}{�C��/h>��PK!����g�word/_rels/document.xml.rels �(����N�0��H�C�;�:`�n#�����N[��U�{{¦u۲K/��G����?���:��*4)K���H�+S��-{��c�#arQ�?�������b�� ��+��E>�q)+���?,AcƟ(�Z?m�!?E|8����`ӽ��<O�?��~�j|���Q�J�#ʥCGJp0�A�W�2a��m��s2~��OG����C��}�W������ a�z֯�n��H��?KG�?���e�cު�"�I�f�'�7,^?�����1r�'�;��*!���Fϔ�}�n,�?���?ܜ`Е��PQ,Q�?K���x߀��)�WT>)�:�88
5���;<oY
Can you please tell me what wrong I have done in this code?
You need to set the response headers and content-type which triggers the browser to treat the response content as a file and not as a web page:
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setHeader("Content-Disposition", "attachment; filename=download.xlsx");
It seems that you are downloading an xlsx file, Try the code below:
public void downoadResume(#PathVariable("id") int id, HttpServletResponse response) {
try {
Applicant applicant = applicantService.getOne(id);
File file = new File(DocumentConstants.DOCUMENTS_PATH + "/" + applicant.getOriginalDocPath());
response.reset();
response.resetBuffer();
response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
response.setContentLength((int) file.length());
response.setHeader("Content-Disposition", "attachment; filename=test.xlsx");
// get your file as InputStream
InputStreamReader is = new InputStreamReader(new FileInputStream(file.getAbsolutePath()));
// copy it to response's OutputStream
org.apache.commons.io.IOUtils.copy(is, response.getOutputStream());
is.close();
response.flushBuffer();
} catch (IOException ex) {
ex.printStackTrace();
} catch (ResourceNotFoundException e) {
e.printStackTrace();
}
}

Categories

Resources