I'm trying to send image to my server to store it to mysql database.
I'm trying to post Formdata with jQuery and receive it like a java MultipartFile and convert it to bytes[]. I found a few ways to do it , but neither is working,
can somebody help me please?
This is my best try:
<form>
<input type="file" id="file"/>
<a onclick="uploadImage()" >Upload</a>
</form>
JS
function uploadImage() {
var formData = new FormData();
formData.append('file', $('#file')[0].files[0]);
$.ajax({
type : 'POST',
url : '/admin/uploadImage',
headers : {
"X-CSRF-TOKEN" : token
},
data : formData,
cache: false,
contentType: false,
processData: false,
});
alert("proso");
}
and JAVA
#RequestMapping(value = "/uploadImage", method = RequestMethod.POST)
public void save(#RequestParam("file") MultipartFile file)
{
try
{
File convFile = new File(file.getOriginalFilename());
convFile.createNewFile();
System.out.println("file: " + convFile.getTotalSpace());
byte[] bFile = new byte[(int) convFile.length()];
FileInputStream fileInputStream = new FileInputStream(convFile);
fileInputStream.read(bFile);
fileInputStream.close();
Files newFile = new Files();
newFile.setFileName("4h");
newFile.setData(bFile);
filesRepository.save(newFile);
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Can anybody help me?
Try following code
#RequestMapping(value = "/uploadImage", method = RequestMethod.POST)
public void save(MultipartHttpServletRequest request)
{
try
{
Iterator<String> itr = request.getFileNames();
while(itr.hasNext()) {
MultipartFile file = request.getFile(itr.next());
if(file != null) {
File convFile = new File(file.getOriginalFilename());
convFile.createNewFile();
System.out.println("file: " + convFile.getTotalSpace());
byte[] bFile = new byte[(int) convFile.length()];
FileInputStream fileInputStream = new
FileInputStream(convFile);
fileInputStream.read(bFile);
fileInputStream.close();
Files newFile = new Files();
newFile.setFileName("4h");
newFile.setData(bFile);
filesRepository.save(newFile);
}
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Related
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();
}
}
this is my file path
public final static String BOOKINGPDFFILE= "D:/Hotels/pdf/";
This below code is what I have written to download pdf from the above resource folder
Pdf="column name in database i used for storing in database"
#RequestMapping(value = "/getpdf/{pdf}", method = RequestMethod.GET)
public void getPdf(#PathVariable("pdf") String fileName, HttpServletResponse response,HttpServletRequest request) throws IOException {
try {
File file = new File(FileConstant.BOOKINGPDFFILE + fileName+ ".pdf");
Files.copy(file.toPath(),response.getOutputStream());
} catch (IOException ex) {
System.out.println("Contract Not Found");
System.out.println(ex.getMessage());
}
}
Here is the way, hope it help.
#RequestMapping(value = "/getpdf/{pdf}", method = RequestMethod.GET)
public void getPdf(#PathVariable("pdf") String fileName, HttpServletResponse response) throws IOException {
try {
File file = new File(FileConstant.BOOKINGPDFFILE + fileName+ ".pdf");
if (file.exists()) {
// here I use Commons IO API to copy this file to the response output stream, I don't know which API you use.
FileUtils.copyFile(file, response.getOutputStream());
// here we define the content of this file to tell the browser how to handle it
response.setContentType("application/pdf");
response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".pdf");
response.flushBuffer();
} else {
System.out.println("Contract Not Found");
}
} catch (IOException exception) {
System.out.println("Contract Not Found");
System.out.println(exception.getMessage());
}
}
You may try something like this:
#RequestMapping(method = { RequestMethod.GET }, value = { "/downloadPdf" })
public ResponseEntity<InputStreamResource> downloadPdf()
{
try
{
File file = new File(BOOKINGPDFFILE);
HttpHeaders respHeaders = new HttpHeaders();
MediaType mediaType = MediaType.parseMediaType("application/pdf");
respHeaders.setContentType(mediaType);
respHeaders.setContentLength(file.length());
respHeaders.setContentDispositionFormData("attachment", file.getName());
InputStreamResource isr = new InputStreamResource(new FileInputStream(file));
return new ResponseEntity<InputStreamResource>(isr, respHeaders, HttpStatus.OK);
}
catch (Exception e)
{
String message = "Errore nel download del file "+idForm+".csv; "+e.getMessage();
logger.error(message, e);
return new ResponseEntity<InputStreamResource>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
And in your web page you can write the link in this way:
download PDF
You need to create an implementation of AbstractPdfView to achieve this.. You can refer this link https://www.mkyong.com/spring-mvc/spring-mvc-export-data-to-pdf-file-via-abstractpdfview/
Here is the Detailed answer for your question.
let me start with the server side code:
Below class is used to create pdf with some random content and return the equivalent byte array outputstream.
public class pdfgen extends AbstractPdfView{
private static ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
public ByteArrayOutputStream showHelp() throws Exception {
Document document = new Document();
// System.IO.MemoryStream ms = new System.IO.MemoryStream();
PdfWriter.getInstance(document,byteArrayOutputStream);
document.open();
document.add(new Paragraph("table"));
document.add(new Paragraph(new Date().toString()));
PdfPTable table=new PdfPTable(2);
PdfPCell cell = new PdfPCell (new Paragraph ("table"));
cell.setColspan (2);
cell.setHorizontalAlignment (Element.ALIGN_CENTER);
cell.setPadding (10.0f);
//cell.setBackgroundColor (new BaseColor (140, 221, 8));
table.addCell(cell);
ArrayList<String[]> row=new ArrayList<String[]>();
String[] data=new String[2];
data[0]="1";
data[1]="2";
String[] data1=new String[2];
data1[0]="3";
data1[1]="4";
row.add(data);
row.add(data1);
for(int i=0;i<row.size();i++) {
String[] cols=row.get(i);
for(int j=0;j<cols.length;j++){
table.addCell(cols[j]);
}
}
document.add(table);
document.close();
return byteArrayOutputStream;
}
}
Then comes the controller code : here the bytearrayoutputstream is converted to bytearray and sent to the client side using the response-entity with appropriate headers.
#RequestMapping(path="/home")
public ResponseEntity<byte[]> render(HttpServletRequest request , HttpServletResponse response) throws IOException
{
pdfgen pg=new pdfgen();
response.setContentType("application/pdf");
response.setHeader("Content-Disposition", "attachment:filename=report.pdf");
byte[] contents = null;
try {
contents = pg.showHelp().toByteArray();
}
catch (Exception e) {
e.printStackTrace();
}
//These 3 lines are used to write the byte array to pdf file
/*FileOutputStream fos = new FileOutputStream("/Users/naveen-pt2724/desktop/nama.pdf");
fos.write(contents);
fos.close();*/
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.parseMediaType("application/pdf"));
//Here you have to set the actual filename of your pdf
String filename = "output.pdf";
headers.setContentDispositionFormData(filename, filename);
headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
ResponseEntity<byte[]> respons = new ResponseEntity<byte[]>(contents, headers, HttpStatus.OK);
return respons;
}
The header should be set to "application/pdf"
Then comes the client side code :
Where you can make ajax request to server to open the pdf file in new tab of the browser
$.ajax({
url:'/PDFgen/home',
method:'POST',
cache:false,
xhrFields: {
responseType: 'blob'
},
success: function(data) {
//alert(data);
let blob = new Blob([data], {type: 'application/pdf'}); //mime type is important here
let link = document.createElement('a'); //create hidden a tag element
let objectURL = window.URL.createObjectURL(blob); //obtain the url for the pdf file
link.href = objectURL; // setting the href property for a tag
link.target = '_blank'; //opens the pdf file in new tab
link.download = "fileName.pdf"; //makes the pdf file download
(document.body || document.documentElement).appendChild(link); //to work in firefox
link.click(); //imitating the click event for opening in new tab
},
error:function(xhr,stats,error){
alert(error);
}
});
Try this
#Controller
#RequestMapping("/download")
public class FileDownloadController
{
#RequestMapping("/pdf/{fileName}")
public void downloadPDFResource( HttpServletRequest request,
HttpServletResponse response,
#PathVariable("fileName") String fileName)
{
//If user is not authorized - he should be thrown out from here itself
//Authorized user will download the file
String dataDirectory = request.getServletContext().getRealPath("/WEB-INF/downloads/pdf/");
Path file = Paths.get(dataDirectory, fileName);
if (Files.exists(file))
{
response.setContentType("application/pdf");
response.addHeader("Content-Disposition", "attachment; filename="+fileName);
try
{
Files.copy(file, response.getOutputStream());
response.getOutputStream().flush();
}
catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
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.
I get the follwing exception when i try to upload a file in spring :
The request sent by the client was syntactically incorrect.
this is how i submit the value through ajax :
function uploadComment(viewName,answers){
var file_data = $("#CIMtrek_daily_originator_comments").val();
alert("file_data "+file_data);
$.ajax({
type : "POST",
url : "CIMtrek_Compliance_Daily_Shipments_FileUpload",
data: {
uploadFile : file_data,
id : '0'
},
success: function (msg) {
global.getElementById("CIMtrek_uploadedFileName").innerHTML=msg;
alert("File Uploaded");
}
});
}
and this is my controller method :
#RequestMapping(value = "/CIMtrek_Compliance_Daily_Shipments_FileUpload", method = RequestMethod.POST)
public String createComments(#RequestParam("uploadFile") MultipartFile uploadItem ) {
System.out.println(" CIMtrek_Compliance_Daily_Shipments_FileUpload : ");
String uploadedFileName="";
try {
String fileName = null;
InputStream inputStream = null;
OutputStream outputStream = null;
if (uploadItem.getSize() > 0) {
inputStream = uploadItem.getInputStream();
System.out.println("size::" + uploadItem.getSize());
fileName = "/WEB-INF/resources/Attachment/"+ uploadItem.getOriginalFilename();
outputStream = new FileOutputStream(fileName);
System.out.println("fileName:" + uploadItem.getOriginalFilename());
int readBytes = 0;
byte[] buffer = new byte[10000];
while ((readBytes = inputStream.read(buffer, 0, 10000)) != -1) {
outputStream.write(buffer, 0, readBytes);
}
outputStream.close();
inputStream.close();
}
uploadedFileName =uploadItem.getOriginalFilename();
} catch (Exception e) {
e.printStackTrace();
}
return uploadedFileName;
}
Please help me to resolve this.
You need to use serialize() instead of val() as below
data: $("#your_form").serialize();
$.ajax({
type : "POST",
contentType:false,
url : "CIMtrek_Compliance_Daily_Shipments_FileUpload",
data: $("#your_form").serialize(),
success: function (msg) {
global.getElementById("CIMtrek_uploadedFileName").innerHTML=msg;
alert("File Uploaded");
}
});
i have followed this to upload file to server. the file is getting uploaded but after uploading the file it gives the page name as the filename.extension.jsp and gives HTTP Status 404 here is the screen shot :
But i want to show the user only the status message saying File is uploaded. how to do this?
Here is my spring controller method:
#RequestMapping(value = "/CIMtrek_Compliance_Daily_Shipments_FileUpload", method = RequestMethod.POST)
public String createComments(
#RequestParam("CIMtrek_daily_originator_comments") MultipartFile uploadItem,
HttpServletRequest request) {
String uploadedFileName = "";
try {
String fileName = null;
InputStream inputStream = null;
OutputStream outputStream = null;
if (uploadItem.getSize() > 0) {
inputStream = uploadItem.getInputStream();
fileName = request.getRealPath("") + "/resources/Attachment/"+uploadItem.getOriginalFilename();
outputStream = new FileOutputStream(fileName);
int readBytes = 0;
byte[] buffer = new byte[10000];
while ((readBytes = inputStream.read(buffer, 0, 10000)) != -1) {
outputStream.write(buffer, 0, readBytes);
}
outputStream.close();
inputStream.close();
}
uploadedFileName = uploadItem.getOriginalFilename();
} catch (Exception e) {
e.printStackTrace();
}
return uploadedFileName;
}
Please help me to find,
Best Regards
Hi #Anto you can do it somethig like this,
#RequestMapping(value = "/CIMtrek_Compliance_Daily_Shipments_FileUpload", method = RequestMethod.POST)
public String createComments(
#RequestParam("CIMtrek_daily_originator_comments") MultipartFile uploadItem,
HttpServletRequest request, ModelMap map) {
String uploadedFileName = "";
...
uploadedFileName = uploadItem.getOriginalFilename();
// ---------------------------------------------------------------------------
if("" != uploadedFileName || null != uploadedFileName) {
map.put("message", new String("File is uploaded."));
} else {
map.put("message", new String("File is not uploaded."));
}
// ---------------------------------------------------------------------------
} catch (Exception e) {
e.printStackTrace();
}
return uploadedFileName;
}
And JSP you put
<c:out value="${message}"></c:out>
I hope help you :)