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
Related
I am trying to send a Json string along with multiple files into my Spring Controller, however it would always give me a 405 Method Not Allowed Error, what am I doing wrong?
Javascript Code:
var formdata = new FormData();
formdata.append('user', JSON.stringify(userData));
files.forEach(file=> {
formdata.append('files', file);
});
jQuery.ajax({
url: "user/submitForm",
type: "POST",
data: formdata,
enctype: 'multipart/form-data',
processData: false,
contentType: false,
success: function (data)
{
console.log("SUCCESS");
},
error: function (request, status, error) {
alert(status + " : " + JSON.stringify(request));
}
});
Controller in Spring:
#PostMapping(value= "/submitForm", consumes = {
MediaType.APPLICATION_JSON_VALUE,
MediaType.MULTIPART_FORM_DATA_VALUE })
public ResponseEntity<?> userRegistration( #RequestPart("user") String user,
#RequestPart("files") List<MultipartFile> files, BindingResult bindingResult) {
ObjectMapper obj = new ObjectMapper();
User newUser = new User();
newUser = obj.readValue(user, User.class);
System.out.println("User : \n"+ newUser.toString());
System.out.println("Files : \n"+ files.toString());
return null;
}
This was the solution that I found from Antonio112009's answer
SOLUTION
#PostMapping(value = "/submitForm")
public ResponseEntity<?> userRegistration(
#RequestParam("user") String user,
#RequestParam(value = "files", required = false) List<MultipartFile> files) {
ObjectMapper obj = new ObjectMapper();
User userObj = new User();
.
.
.
}
I use another solution, who works as expected and are a bit more flexible from my point of view.
Front-end part is in Typescript.
Front-end
var formData = new FormData();
options.files.forEach(function (file) {
formData.append(file.name, file);
});
formData.append("myParam", "coucou");
var xhr = new XMLHttpRequest();
xhr.open("POST", "/rest/upload");
xhr.onload = function () {
var data = JSON.parse(xhr.responseText);
options.callback("success", options.files.map(function (file) {
return {
file: file,
content: data[file.name]
};
}));
};
xhr.send(formData);
Back-end (Java Spring)
#RestController
#RequestMapping(value = "/rest")
public class UploadController {
#PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<Boolean> upload(MultipartHttpServletRequest request) {
// Get param
Object myParam = request.getParameter("myParam");
// Get iteretaor on all files
Iterator<String> iterator = request.getFileNames();
MultipartFile multipartFile = null;
while (iterator.hasNext()) {
multipartFile = request.getFile(iterator.next());
final String fileName = multipartFile.getOriginalFilename();
final String fileSize = String.valueOf(multipartFile.getSize());
// Add logic ....
}
}
return new ResponseEntity(true);
}
I am attempting to send form data with Multipart data (Image) to Spring MVC controller. From my form. image field is non mandatory. so when i call spring controller without input image field, i get below error in browser console.
Failed to load resource: the server responded with a status of 400
(Bad Request)
Html Code:
<input file="file" type="file" id ="file2"/>
AngularjS Code:
$scope.saveData = function (formObj) {
$http({
url: CONTEXT_PATH+'saveFile',
method: "POST",
headers: { 'Content-Type': undefined },
transformRequest: function (data) {
alert(data.files);
var formData = new FormData();
formData.append("model", angular.toJson(data.model));
formData.append("file", data.files);
return formData;
},
data: { model: formObj, files: $scope.file }
}).then(function (response) {
//alert(response);
});
};
app.directive('file', function () {
return {
scope: {
file: '='
},
link: function (scope, el, attrs) {
el.bind('change', function (event) {
var file = event.target.files[0];
scope.file = file ? file : undefined;
scope.$apply();
});
}
};
});
Spring Controller Code:
#RequestMapping(value = "/saveFile")
public #ResponseBody String storeAd(#RequestParam ("model") String adString, #RequestParam ("file") MultipartFile file) throws IOException {
System.out.println("adString > "+adString);
return "OK";
}
When the image is not uploaded, the request is bad because Spring MVC assumes all parameters required unless otherwise defined.
In your case, you should add required = false.
#RequestParam(value = "file", required = false)
Your server code is expecting a request parameter with name "file" but you are not defining it properly.
Change
<input file="file"
To
<input type="file" name="file"
I am new to Spring MVC and I am trying to send my data to Spring-MVC Controller using AJAX, on button click. I have written this code (given below) but I am getting error instead of success. please tell what can be the issue?
AJAX:
function add() {
var name = $('#name').val();
$.ajax({
url : "/addUser",
data : name,
type : "POST",
async: false,
success : function(response) {
alert( response );
},
error : function() {
alert("error....");
}
});
}
JAVA
#RequestMapping(value = "/addUser", method = RequestMethod.POST)
public String addUser(#ModelAttribute("UserTest") String name) {
//task
return name;
}
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);
}
});
});
I have two dropdownlists in Jsp One for state and other for country. As soon as i select country the statelist should be populated automatically with respective lists. But i am getting whole jsp page as response in ajax call.
My ajax Program:
$("select#country").change(function() {
var val=$("#country").val();
alert(val);
$.ajax({
url : 'getstates',
method : 'get',
contentType: 'application/json',
data :{
country : val
},
success: function (data) {
alert("Success Response"+ data);
},
error :function()
{
alert("error");
}
});
My controller program
#RequestMapping(value = "/getstates", method = RequestMethod.GET)
public ModelAndView showstates(#RequestParam(required = false, value = "")
String country,#Valid #ModelAttribute("employee")Login employee,
BindingResult result, Model model) {
HashMap<String,String> stateMap = new HashMap<String,String>();
//put your logic to add state on basis of country
if (country.equals("UnitedStates")) {
stateMap.put("Al","Alaska");
stateMap.put("Tl","Texas");
} else if (country.equals("UnitedKingdom")) {
stateMap.put("Be","Bedfordshire");
stateMap.put("Ber","Berkshire");
} else if (country.equals("India")) {
stateMap.put("Mh","Maharashtra");
stateMap.put("WB","West Bengal");
stateMap.put("KR","Karnataka");
stateMap.put("AP","Andhra Pradesh");
stateMap.put("TN","Tamil Nadu");
}
return new ModelAndView("LoginForm","state" ,stateMap);
}
I am using spring form. I need to get only Staemap as respone but i am getting whole jsp page as response.
I need to get only Staemap as respone but i am getting whole jsp page
as response.
Because you are returning the ModelAndView object with the view here,
return new ModelAndView("LoginForm","state" ,stateMap);
If you need to return the respone alone from the controller method.However you cant print the HashMap directly in the ajax response on your jsp. IMHO you can convert it to JSONArray
JSONArray jarray = JSONArray.fromObject(statemap);
Read ,
send array from controller to a view using JSON in MVC
Sending JSON response from spring controller
loop through json array jquery
#RequestMapping(value="LoadBaselineVersions")
#ResponseBody
public Map<Integer,String> loadBaseNames(#RequestParam(value="projectname") String name,HttpSession session){
return basenameService.getBaselineversions(name);
}
$("#projectname").bind(
'blur',
function() {
$.ajax({
type : 'post',
url : 'LoadBaselineVersions?projectname='
+ $("#projectname").val(),
dataType : 'json',
success : function(data) {
$("#baseversion").empty();
$.each(data, function(val, text) {
$("#baseversion").append(
$('<option></option>').val(text).html(
text));
});
}
});
});