throw different message exception with message body - ajax

I am trying unzipping a zip file which might be empty no files and folder. It was throwing an UnsupportedOperationException therefore I was handling with throw keyword and then giving the message body to jsp page.
try {
boolean upload=unzipUploadedFile(saveZip,folderName);
if(upload)
return ServiceResponse.createSuccessResponse();
else
return ServiceResponse.createFailureResponse("Files cannot be unzipped");
}catch(Exception e) {
e.printStackTrace();
return ServiceResponse.createFailureResponse(e.getMessage());
}
private boolean unzipUploadedFile(File saveZip, String folderName) throws Exception {
//Open the file
try(ZipFile file = new ZipFile(saveZip.getCanonicalPath()))
{
FileSystem fileSystem = FileSystems.getDefault();
//Get file entries
Path inputpath=fileSystem.getPath(file.getName());
Enumeration<? extends ZipEntry> entries = file.entries();
//We will unzip files in this folder
File directory=new File(zipFilePath.concat(folderName));
if(!directory.exists()) {
directory.mkdir();
}
//Iterate over entries
while (entries.hasMoreElements())
{
ZipEntry entry = entries.nextElement();
String abc[]=entry.getName().split("/");
//Else create the file
if(!entry.isDirectory())
{
InputStream is = file.getInputStream(entry);
BufferedInputStream bis = new BufferedInputStream(is);
String uncompressedFileName = zipFilePath +folderName+"/"+ abc[abc.length-1];
Path uncompressedFilePath = fileSystem.getPath(uncompressedFileName);
if(Files.notExists(uncompressedFilePath))
Files.createFile(uncompressedFilePath);
FileOutputStream fileOutput = new FileOutputStream(uncompressedFileName);
while (bis.available() > 0)
{
fileOutput.write(bis.read());
}
fileOutput.close();
System.out.println("Written :" + entry.getName());
is.close();
bis.close();
}
}
file.close();
Files.deleteIfExists(inputpath);
fileSystem.close();
}catch(UnsupportedOperationException e)
{
throw new UnsupportedOperationException("Uploaded zip does not contain proper file or folder");
}
catch(Exception e) {
throw new Exception("File unizipping unsuccessful");
}
return true;
}
But if I add the zip with all files in it still it is giving me Uploaded zip does not contain proper file or folder at the UI end
Jsp page where I called the controller code
$
.ajax({
type : 'POST',
url : baseUrl + url,
data : data,
cache: false,
dataType: 'json',
processData: false,
contentType: false,
success: function(dataset){
console.log(dataset.error);
document.getElementById("spinner").style.display = "none";
$('#reportError').modal('show');
document.getElementById('uploadError').innerHTML="<center>"+dataset.error+"</center>";
document.getElementById('error_title').innerHTML="Upload Failure";
},
error : function(e){
console.log(e);
}
});
Stack trace
java.lang.UnsupportedOperationException: Uploaded zip does not contain proper file or folder
at com.tata.green.controller.GreenBackendServiceController.unzipUploadedF
ile(GreenBackendServiceController.java:580)
at com.tata.green.controller.GreenBackendServiceController.uploadServerDe
tails(GreenBackendServiceController.java:509)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.
java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAcces
sorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvok
e(InvocableHandlerMethod.java:205)

Related

Error in downloading zipped parent folder from app using Spring Boot and Java script

I am working on Spring Boot application where I need to provide download zipped report files feature. In order to do that I am converting zipped report files to byte array and then trying to send it at the browser side. I am able to download the zipped report file but when I try to extract it gives an error message that 'The Compressed zipped folder is invalid.' Please find the code snippet below:
Server Side Code:
#ResponseBody
#RequestMapping(value = "/downloadResult", method = RequestMethod.POST, produces="application/zip" )
public byte[] downloadResult(#RequestBody ResultParamsVO resultParamsVO, HttpServletRequest request,
HttpServletResponse response) {
byte[] result = null;
try {
HttpSession session = request.getSession(false);
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String user = auth.getPrincipal().toString();
String testType = null;
if (session.getAttribute("testType") != null) {
testType = session.getAttribute("testType").toString();
}
result = jobService.downloadResult(resultParamsVO, testType, user);
response.setStatus(HttpServletResponse.SC_OK);
response.addHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=resultDownload1.zip");
} catch (Exception e) {
logger.error("Error in getResult() for job id - " + resultParamsVO.getJobId(), e.getMessage());
e.printStackTrace();
}
return result;
}
Browser Side Ajax Call:
$.ajax({
type: "POST",
url: "/downloadResult",
contentType: "application/json",
data: JSON.stringify(resultParamsVO),
success: function(result) {
var downloadUrl = window.URL.createObjectURL(new Blob([result], {type: "application/zip"}));
var a = document.createElement("a");
a.href = downloadUrl;
a.download = "resultDownload.zip";
document.body.appendChild(a);
a.click();
}
});
Please help. Thanks in advance.

How to upload picture in Spring and Angular2

I want to upload picture in my app this is my Angular 2 code
constructor () {
this.progress = Observable.create(observer => {
this.progressObserver = observer
}).share();
}
public makeFileRequest (url: string, params: string[], files: File[]):
Observable<any> {
return Observable.create(observer => {
let formData: FormData = new FormData(),
xhr: XMLHttpRequest = new XMLHttpRequest();
for (let i = 0; i < files.length; i++) {
formData.append("uploads[]", files[i], files[i].name);
}
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
observer.next(JSON.parse(xhr.response));
observer.complete();
} else {
observer.error(xhr.response);
}
}
};
xhr.upload.onprogress = (event) => {
this.progress = Math.round(event.loaded / event.total * 100);
this.progressObserver.next(this.progress);
};
xhr.open('POST', url, true);
xhr.send(formData);
});
}
And this is my spring controller
#RequestMapping(value = "/upload", method = RequestMethod.POST)
#ResponseBody
public ResponseEntity<?> uploadFile(
#RequestParam("file") MultipartFile uploadfile) {
try {
// Get the filename and build the local file path (be sure that the
// application have write permissions on such directory)
String filename = uploadfile.getOriginalFilename();
String directory = "/assets/images";
String filepath = Paths.get(directory, filename).toString();
// Save the file locally
BufferedOutputStream stream =
new BufferedOutputStream(new FileOutputStream(new File(filepath)));
stream.write(uploadfile.getBytes());
stream.close();
}
catch (Exception e) {
System.out.println(e.getMessage());
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
return new ResponseEntity<>(HttpStatus.OK);
}
And I get this error
ERROR {"timestamp":1498220487868,"status":400,"error":"Bad Request","exception":"org.springframework.web.multipart.support.MissingServletRequestPartException","message":"Required request part 'file' is not present","path":"/webapp/api/picture/upload"}
You specify #RequestParam("file"), which means Spring waits for an argument with the key file, but you append your data with the key uploads.
Also, as said by #ledniov, your are receiving an array of multipart files, not only one.
Corrections if you want to use the key file:
// Front-End: change "uploads" to "file"
formData.append("file[]", files[i], files[i].name);
// Back-End: takes a MultipartFile array
#RequestParam("file") MultipartFile[] uploadfile
Corrections if you want to use the key uploads:
// Back-End: change "file" to "uploads" and takes a MultipartFile array
#RequestParam("uploads") MultipartFile[] uploadfile

Returning zip file from REST to client not popping up the file

I am trying to downloada zip file sent from a REST by adding the Content-Type and the Content-Disposition doing the following:
Server-side
#Produces("application/x-zip-compressed")
public Response export(#PathParam("username") String username,
#Context UriInfo ui) {
long timeStamp = new Date().getTime();
String exportedFolder = "/home/madmin/pods/"+username+"/download/";
String Path = ui.getRequestUri().toString()
.replace(replaceMe + username, "");
Path = Path.replace("http://", "https://");
Path = Path.replace(",system/export", "");
String outputZipFile = exportedFolder+"exported_on_"+timeStamp+".zip";
String sourceFolder = null;
File file = new File(exportedFolder);
if (!file.exists()) {
if (file.mkdirs()) {
System.out.println("Directory is created!");
} else {
System.out.println("Failed to create directory for exporting!");
//return ;
}
}
constructGraphs cGraphs = new constructGraphs(Path, username);
sourceFolder = cGraphs.writeGraphFiles();
generateZipFile appZip = new generateZipFile(sourceFolder,outputZipFile);
appZip.generateFileList(new File(sourceFolder));
appZip.zipIt(outputZipFile);
//Read the outputZipFile as inputStream and return it
FileInputStream fileIs = null;
try {
fileIs = new FileInputStream(outputZipFile);
} catch (IOException e) {
throw new WebApplicationException(404);
}
String fileName= outputZipFile.substring(outputZipFile.lastIndexOf("/")+1, outputZipFile.length());
return Response.status(Status.OK).entity(fileIs).header("Content-Disposition","attachment; filename = "+fileName).build();
}
Client-side:
The client side on the other hand is expecting application/x-zip-compressed as follows:
$http({
method: 'GET',
url: uri,
headers: {
'Accept': 'application/x-zip-compressed'
},
withCredentials: true
}).
success(function(data, status, headers) {
if (status == 200 || status == 201) {
notify('Success', 'Node exported.');
}
}).
error(function(data, status) {
if (status == 401) {
notify('Forbidden', 'Authentication required to edit the resource.');
} else if (status == 403) {
notify('Forbidden', 'You are not allowed to edit the resource.');
} else {
notify('Failed', status + " " + data);
}
});
The file is not popping up, instead I see the input stream in the response.
Is there anything wrong I am doing here? Any help would be really appreciated.
It is not possible with AJAX and I assume you are using angularjs http serivce in this case. See: Why threre is no way to download file using ajax request?.
You have different options to solve your problem.
For instance: easiest way to open a download window without navigating away from the page
or How do you serve a file for download with AngularJS or Javascript?

Spring Ajax file upload

I am using jquery ajaxSubmit function for submitting my form. I also have file upload field in the form.
Here's the code of ajaxSubmit function.
$('#wizard-p-7').submit(function(e) {
$(".validationMessage").hide();
e.preventDefault();
var formURL = $(this).attr("action");
$(this).ajaxSubmit({
url : formURL,
async : false,
contentType: 'multipart/form-data',
success : function(data) {
if (data == "version match.") {
check = true;
} else {
check = false;
}
},
error : function(jqXHR,
textStatus,
errorThrown) {
alert("error:"+errorThrown);
window.location = "<%=application.getContextPath()%>/pages/error/globalError.jsp";
}
});
e.preventDefault(); //STOP default action
// e.unbind(); //unbind. to stop multiple form submit.
return false;
});
Here is my controller method
#RequestMapping(value = "/sectioneight", method = RequestMethod.POST)
public #ResponseBody Object sectioneight(#ModelAttribute("iepDTO") ProjectDTO iepDTO,
#RequestParam("id") String id) {
try {
List<MultipartFile> files = iepDTO.getPolicyBriefFiles();
if(files!=null){
for(MultipartFile file : files){
String filePath = "C:/temp/" + file.getOriginalFilename();
File dest = new File(filePath);
file.transferTo(dest);
}
}
}
catch (Exception e) {
System.out.println("Exception: "+e.getMessage());
logger.error("ProjectController - sectioneight : "+ e.getMessage());
}
return "redirect:home";
}
Now the problem is if I select a file for uploading and submit the form everything works fine. But if I submit the form without selecting file it gives 400 Bad request error in the browser console. Can't find what is wrong.
Any clue?
Solved. Problem was because of ajax. If I don't select a file it sends null string in place of file.
The solution is now I check before submitting the form if file is selected or not. If not, I disable the field with jquery
if($("#policyBriefFiles").val()==""){
$("#policyBriefFiles").prop('disabled', true);
}
Life's good:)

File upload is not working in spring using jquery-ajax

This is my form :
<form name="CIMtrek_Compliance_Daily_Shipments" enctype="multipart/form-data">
<input type="file" id="CIMtrek_comments" name="CIMtrek_comments" value="" />
<button id="upload" onclick="uploadCommentFile()">Upload</button>
</form>
and this is my ajax call using jquery :
function uploadCommentFile(){
$("#upload").live("click", function() {
var file_data = $("#CIMtrek_comments").prop("files")[0]; // Getting the properties of file from file field
var form_data = new FormData(); // Creating object of FormData class
form_data.append("file", file_data) // Appending parameter named file with properties of file_field to form_data
//form_data.append("user_id", 123) // Adding extra parameters to form_data
$.ajax({
type: 'POST',
url: "/CIMtrek_Compliance_Daily_Shipments_FileUpload",
dataType: 'script',
cache: false,
contentType: false,
processData: false,
data: {
uploadFile: file_data
},
success: function (msg) {
global.getElementById("CIMtrek_uploadedFileName").innerHTML=msg;
}
})
})
}
and this is my spring controller :
#RequestMapping(value = "/CIMtrek_Compliance_Daily_Shipments_FileUpload", method = RequestMethod.POST)
public String createComments(#RequestParam("uploadFile") CommonsMultipartFile uploadItem,
HttpServletRequest request) {
String uploadedFileName="";
try {
MultipartFile file = uploadItem;
String fileName = null;
InputStream inputStream = null;
OutputStream outputStream = null;
if (file.getSize() > 0) {
inputStream = file.getInputStream();
System.out.println("size::" + file.getSize());
fileName = request.getRealPath("") + "/WEB-INF/resources/Attachment"+ file.getOriginalFilename();
System.out.println("path : "+request.getRealPath("") + "/WEB-INF/resources/Attachment");
outputStream = new FileOutputStream(fileName);
System.out.println("fileName:" + file.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 =file.getOriginalFilename();
} catch (Exception e) {
e.printStackTrace();
}
return uploadedFileName;
}
but i get the following exception when i click on upload button :
HTTP Status 400 -
The request sent by the client was syntactically incorrect.
what could be the problem, Please help me to identify.
Best Regards.
Follow this one it helped and solved my problem :

Resources