Delete File from Disk using AJAX and Spring Boot - java

I am trying to delete a file from the disk ( Local or Server ) using Ajax and Spring boot technologies.
So far i have tried this:
Ajax/jquery:
$(".ct-color-specs").on("click",".color-spec-file-delete",function() {
var deletedFileName = $(this).parents(".ct-attached-color-spec-files").find("a").text();
$.ajax({
url : "/Application/removeFile/"+deletedFileName",
type: 'DELETE',
success: function (res) {
console.log(data);
}
});
});
Controller:
#RequestMapping(value = "/removeFile",produces="text/html", method = RequestMethod.DELETE)
public String removeFileHandler(#PathVariable("deletedFileName") String filepath, Model model) {
String removeFileCheck = "false";
try{
System.out.println("Delete filepath from AJX");
File file = new File(filepath);
if(file.delete()){
System.out.println(file.getName() + " is deleted!");
removeFileCheck="true";
}else{
System.out.println("Delete operation is failed.");
}
}catch(Exception e){
e.printStackTrace();
}
model.addAttribute("checkList", removeFileCheck);
return "p/view";
}
Error:
"Not Found" message : "No message available" path :
"/Application/removeFile/File.pdf" status : 404

You have written the #RequestMapping(value = "/removeFile" ...) in wrong format
Path variable in spring is to be used like below
#RequestMapping(value="/user/{userId}/roles/{roleId}",method = RequestMethod.GET)
public String getLogin(#PathVariable("userId") String userId,
#PathVariable("roleId") String roleId){
System.out.println("User Id : " + userId);
System.out.println("Role Id : " + roleId);
return "hello";
}

I will be writing answer here , as i have solved with below code.
Controller:
#RequestMapping(value = "/removeFile/{deletedFileName}", method = RequestMethod.GET)
public String removeFileHandler(#PathVariable("deletedFileName") String filepath, Model model) {
.....
}
AJAX/jquery:
$(".ct-color-specs").on("click",".color-spec-file-delete",function() {
var deletedFileName = $(this).parents(".ct-attached-color-spec-files").find("a").text().split('/').pop().split('\\').pop();;
alert("deletedFileName--->" + deletedFileName);
$.ajax({
url : "/Application/removeFile/"+deletedFileName,
type: 'GET',
success: function (res) {
console.log(data);
}
});
});

Related

Edit files online using Office 365 using WOPI not working - Java

I have a requirement where from my application I have to edit files using office 365. I have used WOPI and it was working fine before, but now I'm getting the following error.
When I contacted the support team, they said WOPI CheckFileInfo is not called, so I explicitly called still the issue persists.
Below is my code,
function submit(docId, type) {
var WOPISrc = "WOPISrc=https://" + host +"/wopi/files/" + docId;
if (type == 'word') {
$('#office_form_online').attr('action', 'https://word-edit.officeapps.live.com/we/wordeditorframe.aspx?edit=1&ui=en-US&rs=en-US&IsLicensedUser=1&hid=1234&sc=edit_form&' + WOPISrc);
} else if (type == 'excel') {
$('#office_form_online').attr('action', 'https://excel.officeapps.live.com/x/_layouts/xlviewerinternal.aspx?edit=1&ui=en-US&rs=en-US&IsLicensedUser=1&hid=1234&sc=edit_form&' + WOPISrc);
} else if (type == 'powerpoint') {
$('#office_form_online').attr('action', 'https://powerpoint.officeapps.live.com/p/PowerPointFrame.aspx?PowerPointView=EditView&ui=en-US&rs=en-US&IsLicensedUser=1&hid=1234&sc=edit_form&' + WOPISrc);
} else if (type == 'pdf') {
$('#office_form_online').attr('action', 'https://word-view.officeapps.live.com/wv/wordviewerframe.aspx?PdfMode=1&ui=en-US&rs=en-US&IsLicensedUser=1&hid=1234&sc=edit_form&' + WOPISrc);
} else {
return false;
}
var promise = createWOPIToken(docId);
promise.success(function (data) {
$.ajax({
url: "https://" + host + "/wopi/files/" + docId,
type: "GET",
data: {
access_token: data.token
},
async: false,
dataType: "json",
contentType: "application/json; charset=utf-8",
error: function (jqXHR, textStatus, errorThrown) {
return '';
},
success: function (data1) {
console.log(data1);
$.ajax({
url: "https://" + host + "/wopi/files/" + docId + "/content",
type: "GET",
data: {
access_token: data.token
},
async: false,
dataType: "json",
contentType: "application/json; charset=utf-8",
error: function (jqXHR, textStatus, errorThrown) {
return -1;
},
success: function (contents) {
$('#office_access_token_online').val(data.token);
$('#office_access_token_ttl_online').val(0);
var frameholder = document.getElementById('frameholder_online');
$(frameholder).show();
closeiFrame();
var office_frame = document.createElement('iframe');
office_frame.src = 'https://"+ host + "/wopi/files/" ' + docId + "?access_token="+data.token;
office_frame.name = 'office_frame_online';
office_frame.id = 'office_frame_online';
office_frame.title = 'Office Online Frame';
office_frame.setAttribute('allowfullscreen', 'true');
office_frame.setAttribute('sandbox',
'allow-scripts allow-same-origin allow-forms allow-popups allow-top-navigation allow-popups-to-escape-sandbox');
frameholder.appendChild(office_frame);
document.getElementById('office_form_online').submit();
showCloseButton();
}
});
}
});
});
}
Java Code
#Override
#GET
#Path("/files/{fileId}")
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public Response checkFileInfo(
#NotNull #PathParam("fileId") Integer fileId,
#NotNull #QueryParam("access_token") String access_token) {
return Response.ok().entity(fileInfo).build();
}
}
#Override
#GET
#Path("/files/{fileId}/content")
#Produces(MediaType.APPLICATION_JSON)
public Response getFile(
#NotEmpty #PathParam("fileId") Integer fileId,
#QueryParam("access_token") String access_token) {
byte[] data = new byte[(int) content().length()];
DataInputStream dataIs = new DataInputStream(content.getBinaryStream());
dataIs.readFully(data);
return Response.ok(new ByteArrayInputStream(data)).build();
}
#Override
#POST
#Path("/files/{fileId}/contents")
#Transactional
public Response putFile(#PathParam("fileId") Integer fileId,
#QueryParam("access_token") String access_token, byte[] bytes) {
save(BlobProxy.generateProxy(SecurityWrapper.encrypt(bytes)));
return Response.ok().build();
}
The API calls are returning responses but it's not opening files.
EDIT
When I try hitting the below URL (which is used to open files online), without any source, still it shows as Service Unavailable.
https://word-edit.officeapps.live.com/we/wordeditorframe.aspx?
Is it because of it, that my code isn't working? And in the test server, it's a different error, we ran into a problem.
And this is the console error
Any help is appreciated.
Thank you.

Angular 5 + Spring boot image upload

I am trying to upload an image from angular to spring boot rest. but it throws
org.springframework.web.multipart.MultipartException: Current request is not a multipart request
at org.springframework.web.method.annotation.RequestParamMethodArgumentResolver.handleMissingValue(RequestParamMethodArgumentResolver.java:190) ~[spring-web-4.3.13.RELEASE.jar:4.3.13.RELEASE]
I am new to both the technologies. Help me upload the file.
Here is the code.
RestController
public ResponseMessage addUser(#RequestParam("profileImage") MultipartFile profileImage,
#RequestParam("user") User user) {
try {
if (userService.doesUserExist(user.getUsername())) {
return new ResponseMessage("The username is not available; please choose a different username", 200);
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
String extension = FilenameUtils.getExtension(profileImage.getOriginalFilename());
storageService.storeFile(profileImage, user.getUsername() + "." + extension, profilePicturePath);
user.setProfilePicturePath(profilePicturePath + "/" + user.getUsername() + "." + extension);
userService.addUser(user);
return new ResponseMessage(user.getUsername() + " was added successfully!", 200);
}
Angular Service
addUser(user:User,profileImage:File){
const formData:FormData = new FormData();
formData.append('profileImage', profileImage);
formData.append('user',JSON.parse(JSON.stringify(user)));
return this.http.post<ResponseMessage>("/api/admin/user/new_user",formData,this.postHttpOptions);
}
Angular Component
setImage(files:FileList){
this.newProfileImage = files.item(0);
}
upload(){
if (this.newUser.password == this.newUser.confirmPassword) {
this.userService.addUser(this.newUser,this.newProfileImage).subscribe(
res => {
this.responseMessage = res;
alert(this.responseMessage.message);
},
err => {
alert("Error Adding the user: " + err.message);
}
);
}
}
Angular Template
<input type='file' id="imgInp" (change)="setImage($event.target.files)" />
I got it.
The changes I made..
Instead of #RequestParam I added #Requestpart
Instead of #RequestParam User user I added #RequestPart String user; then converted String to user using ObjectMapper.
On the client side, I removed'ContentType = application/Json' and mentioned no content type
Here is the code
public String addUser(#RequestPart("profileImage") MultipartFile profileImage,
#RequestPart("user") String userString) throws JsonParseException, JsonMappingException, IOException {
User user = new ObjectMapper().readValue(userString, User.class);
}

415 (Unsupported Media Type) with jquery

I am new to using a RESTful API and I don't know why it is showing this error.
I am posting the values through jQuery. Do I need to do something else? This is my jQuery code:
Updated : Now it is showing 405 (Method Not Allowed)
$(document).ready(function(){
$("#patsubmit").click(function() {
var firstName = $("#firstName").val();
var lastName = $("#lastName").val();
var mobileNumber = $("#mobileNumber").val();
var emailId = $("#emailId").val();
var dataString = '{"firstName":"'+ firstName + '","lastName":"' + lastName + '","mobileNumber":"' + mobileNumber + '", "emailId":"' + emailId+'"}';
console.log(dataString);
if(firstName=='' )
{
alert("nothing in it");
}
else
{
$.ajax({
type: 'POST',
url : '/geniedoc/api/patient/register',
data: dataString,
contentType: 'application/json',
dataType: 'json',
headers: {'Content-Type':'application/json'}
success: function(){ // Uncaught SyntaxError: Unexpected identifier
console.log();
}
});}
return false;
});
});
This is my Java API. MAIN_PATIENT = api/patient and RestURIConstants.REGISTER = register
#RestController
#RequestMapping(value = RestURIConstants.MAIN_PATIENT)
public class PatientRestController extends AbstractController implements RestURIConstants, GenieDocConstants{
private static final Logger logger = Logger.getLogger(UserRestController.class);
#RequestMapping(value = RestURIConstants.REGISTER, method = RequestMethod.POST, consumes ="application/json")
public #ResponseBody ModelMap registerPatient(HttpServletRequest request, #RequestBody PatientVo patientVo){
logger.info("registerPatient : Start");
long startTime = System.currentTimeMillis();
ModelMap map = new ModelMap();
PatientVo patVo;
try {
if(patientVo.getFirstName() == null) {
map.addAttribute(STATUS_CODE, FAILURE);
map.addAttribute(STATUS_MESSAGE, this.env.getProperty(MESSAGE_FIRST_NOT_EMPTY));
} else if(patientVo.getEmailId() == null) {
map.addAttribute(STATUS_CODE, FAILURE);
map.addAttribute(STATUS_MESSAGE, this.env.getProperty(MESSAGE_EMAIL_NOT_EMPTY));
} else if(patientVo.getEmailId() == "") {
map.addAttribute(STATUS_CODE, FAILURE);
map.addAttribute(STATUS_MESSAGE, this.env.getProperty(MESSAGE_EMAIL_NOT_EMPTY));
} else if (patientVo.getMobileNumber() == null) {
map.addAttribute(STATUS_CODE, FAILURE);
map.addAttribute(STATUS_MESSAGE, this.env.getProperty(MESSAGE_MOBILE_NOT_EMPTY));
} else {
patVo = this.patientManagementService.provisionPatient(patientVo);
if (patVo != null) {
map.addAttribute("patientId", patVo.getEmailId());
map.addAttribute(STATUS_CODE, SUCCESS_STATUS_CODE_REGPATIENT);
map.addAttribute(STATUS_MESSAGE, this.env.getProperty(SUCCESS_STATUS_CODE_REGPATIENT));
} else {
map.addAttribute(STATUS_CODE, ERROR_STATUS_CODE_REG);
map.addAttribute(STATUS_MESSAGE, this.env.getProperty(ERROR_STATUS_CODE_REG));
}
}
} catch (MongoDBDocumentNotFoundException e) {
map.addAttribute(STATUS_CODE, ERROR_STATUS_CODE_REGPATIENT);
map.addAttribute(STATUS_MESSAGE,this.env.getProperty(ERROR_STATUS_CODE_REGPATIENT));
logger.error("Error : " + e.getMessage());
//e.printStackTrace();
} catch (UserAreadyExsistException e) {
map.addAttribute(STATUS_CODE, ERROR_STATUS_CODE_REGPATIENT);
map.addAttribute(STATUS_MESSAGE, this.env.getProperty(ERROR_STATUS_CODE_REGPATIENT));
logger.error("Error : " + e.getMessage());
//e.printStackTrace();
}
logger.debug("Exit: Total Time Taken: "+ (System.currentTimeMillis() - startTime));
return map;
}
You need to set the Content-Type Header to application/json
$.ajax({
type: 'POST',
url: '/geniedoc/api/patient/register',
data: dataString,
headers: {
'Content-Type':'application/json'
}
.....
}
In your spring controller you are defining, that only content of MIME Type application/json is accepted. Because standard content type text/plain the Spring controller does not accept your request and send back a status code 415 (Media type not supported)
Edit: As user6409738 mentioned, you need to send your data in json format. Otherwise the Spring Controller will cause an exception parsing the body.
For example the solution posted by Yagnesh Agola
var dataString = '{"firstName":"'+ firstName + '","lastName":"' + lastName + '","mobileNumber":"' + mobileNumber + '","emailId":' + emailId+'"}';
It depends what your PatientVo Class is looking like
Data you have send to server from client is not in JSON format.
var dataString = 'firstName='+ firstName + '&lastName=' + lastName + '&mobileNumber=' + mobileNumber + '&emailId=' + emailId;
Above line is used to send data string to server which is not in JSON format it is simple query string.
Either you can convert above string in JSON format
var dataString = '{"firstName":"'+ firstName + '","lastName":"' + lastName + '","mobileNumber":"' + mobileNumber + '","emailId":"' + emailId+'"}';
OR
You can directly submit form data in JSON using below code.
var formData = JSON.stringify($("#myForm").serializeArray());
add contentType parameter when use jQuery Ajax
$.ajax({
type : "POST",
contentType : 'application/json',
url : "/geniedoc/api/patient/register",
data : JSON.stringify({"param1" : "param1", "param2":2})
})
remove consumer = "application/json" in your request-mapping definition, (it's not necessary, SpringMVC will auto detect right converter)
because U use #RequestBody in springMVC controller, then SpringMVC will convert the argument with RequestResponseBodyMethodProcessor which use default converters to resolve the argument. default converters list is:
public RequestMappingHandlerAdapter() {
StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter();
stringHttpMessageConverter.setWriteAcceptCharset(false); // see SPR-7316
this.messageConverters = new ArrayList<HttpMessageConverter<?>>(4);
this.messageConverters.add(new ByteArrayHttpMessageConverter());
this.messageConverters.add(stringHttpMessageConverter);
this.messageConverters.add(new SourceHttpMessageConverter<Source>());
this.messageConverters.add(new AllEncompassingFormHttpMessageConverter());
}
For your situation, MappingJackson2HttpMessageConverter is expect to be used to resolve the argument. And here is the definition of MappingJackson2HttpMessageConverter, it need MediaType of application/json
public MappingJackson2HttpMessageConverter(ObjectMapper objectMapper) {
super(objectMapper, MediaType.APPLICATION_JSON_UTF8,
new MediaType("application", "*+json", DEFAULT_CHARSET));
}

500 Internal Server Error when calling ajax in spring

I am using Spring MVC and I have an AJAX which is used to delete selected user. It's working fine on my local system but when I tried to run the same code on development server I'm getting
500 Internal Server Error
I did google to figure out what is wrong with my code but I'm not able to figure out anything till now. Any help will be appreciated.
AJAX function in my JSP file:
$('.del-btn .userId').click(function(){
var userId = $(this).attr("alt");
var data = 'userId='+ userId;
$.ajax({
type: 'POST',
url: '${pageContext.servletContext.contextPath}/deleteUser',
data: data,
success: function(response) {
$('#submitkpi').submit();
}
});
});
deleteUser function in Controller:
#RequestMapping(value = "/deleteUser", method = RequestMethod.POST)
public #ResponseBody Map<String, ? extends Object> deleteKpi(#ModelAttribute(value = "userId") String userId, BindingResult result) {
if (!userId.isEmpty()) {
userService.deleteUser(userId);
return Collections.singletonMap("ok", true);
}
return Collections.singletonMap("errorMsg", "Unable to complete your request!");
}
Can you try this?!
$('.del-btn .userId').click(function(){
var userId = $(this).attr("alt");
$.ajax({
url: 'deleteUser',
data: ({
userId : userId,
}),
success: function(response) {
alert(response)
}
});
});
Controller
#RequestMapping("/deleteUser")
#ResponseBody
public String deleteKpi(#RequestParam(value = "userId") Long userId, HttpSession session) {
if (null != userId) {
userService.deleteUser(userId);
return "Ok";
}
return "NotOk";
}

jsp upload .vcf file to read mobile numbers

How to read .vcf file in jsp or how to pass .vcf file from html to controller.
I am using spring mvc.I want to read contacts from .vcf.
My jsp code:
<span><input type="file" id="vcfFile" name="vcfFile" /> </span>
jquery code :
$("#vcfUpload").click(function (){
var reader = new FileReader();
reader.onloadend = function(){
$
.ajax({
url : "../acquaintance/readingContactsFromVcfFile?vcfFileData="+reader,
type : "post",
contentType : "application/json; charset=utf-8",
cache : false,
dataType : "json",
success : function(data) {
alert(data.message);
}
});
};
reader.readAsText(document.getElementById('vcfFile').files[0]);
});
controller code:
#RequestMapping(value = { "/readingContactsFromVcfFile" }, method = RequestMethod.POST)
public #ResponseBody
ModelMap readContactsFromVcfFile(#RequestParam(value = "vcfFileData")Object vcfData) throws UserServiceException {
log.info("vcf file reading"+ vcfData);
ModelMap modelMap = new ModelMap();
try {
List<VCard> Vcards = Ezvcard.parseHtml((String) vcfData).all();
for (VCard vcard : Vcards) {
log.info("name"+vcard.getFormattedName().getValue());
}
modelMap.addAttribute("message","success");
} catch (Exception IoExp) {
log.info("exception while reading contacts from vcf file",IoExp);
modelMap.addAttribute("message","failed");
}
return modelMap;
}
And i am using Vcard for external :https://code.google.com/p/ez-vcard/wiki/Examples#Example_1.1:_Reading_from_a_plain-text_vCard

Categories