Im trying to fetch photo of a particular userId which is stored in the database,
Im able to generate response from the API as shown:
but it is received in the error part of the getPhotopath() method of controller as shown:
HTML:
<div class="col-md-3 " ng-init="modifyphoto()" >
<img class="smaller" ng-src="fetchedimg" ng-model="fetchedimg"><br>
<p>{{userName}}</p>
<div ng-model="userType">
<p>{{userType | UserFilter}}</p>
</div>
<div ng-controller="AskController">
<button class="btn btn-default" ng-click="gotouserdetails()">View
My Details</button>
</div>
</div>
Controller:
$scope.modifyphoto = function() {
$scope.getPhotoPath();
if($scope.userPhoto==null){
$scope.fetchedimg=$scope.defaultimg;
}
else{
$scope.fetchedimg=$scope.userPhoto;
}
};
$scope.getPhotoPath = function() {
var obj = JSON.parse($cookies.get('user'));
$scope.passUserId = obj.userId;
$http.get(URI + "user/getphoto"+"/"+$scope.passUserId).then(
function(response) {
alert("hifrsegfsfgv");
alert(response.data.message);
$scope.userPhoto=response.data.userPhoto;
}, function(response) {
alert("hi");
alert(response.data);
$scope.userPhoto =null;
alert("danger"+response.data.userPhoto);
});
};
API:
#Path("getphoto/{an}")
#GET
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public Response getPhoto(#PathParam("an") String userId) throws Exception {
String returnValue = null;
Response response = null;
User user = null;
try {
System.out.println(userId);
UserService userService = Factory.createUserService();
String photoPath=userService.getPhotoPath(userId);
user = new User();
user.setUserPhoto(photoPath);
System.out.println(photoPath);
returnValue = JSONParser.toJson(user);
System.out.println(returnValue);
response = Response.status(Status.OK).entity(returnValue).build();
} catch (Exception e) {
String errorMessage = AppConfig.PROPERTIES.getProperty(e.getMessage());
User user1 = new User();
user1.setMessage(errorMessage);
String returnString = JSONParser.toJson(user1);
response = Response.status(Status.SERVICE_UNAVAILABLE).entity(returnString).build();
}
return response;
}
Im not understanding if the status is OK in backend then why it is recieved in the error part?
Try returning your image in base64 format to avoid JSON Parse errors. and bind that image to the img tag
Related
Hello i will tell you step by step,what i did,
1.I have HTML page named ManualChargesListV2.html,when page loads need to load the data in the Dropdown,so i use thymeleaf to show...
Here is #Controller Code
#GetMapping(value="/manualbillentry")
public ModelAndView doFetchUnitCharges(HttpSession session)
{
ModelAndView model = new ModelAndView();
WrpSession wrpsession = new WrpSession();
wrpsession = (WrpSession) session.getAttribute("totalObj");
try {
model.setViewName("ManualChargesListV2");
List<EntSetCharges> flatBillsManualList = new ArrayList<>();
flatBillsManualList = serbilldetails.doFetchUnitCharges(wrpsession);
model.addObject("manuallist",flatBillsManualList);
}
catch (Exception e){
e.printStackTrace();
}
return model;
}
2.The html page loads the data in dropdown perfectly,when choosing dropdown again need to hit the controller to show the data regarding selected dropdown value so i use to code like
<div class="form-group col-md-6">
<label for="chargelist">Select Charge *</label>
<select id="chargelist" class="form-control"
ng-model="selectedcharge"
ng-change="getChargeDetails(selectedcharge)">
<option> Select</option>
<option th:each="manualunitcharge:${manuallist}"
th:value="${manualunitcharge.pkSetCharges}"
th:text="${manualunitcharge.fkAssignCharges.chargeName}"></option>
</select>
</div>
it will call AngularJS ng-change="getChargeDetails(selectedcharge) method,it successfully hits the controller incl selected data.And Sends the data
#GetMapping(value = "manualbillentry/showmanuallist/{chargeid}")
private ResponseMsg doFetchManualChargesList(#PathVariable("chargeid")int chargeid,HttpSession session)
{
ResponseMsg response = new ResponseMsg();
WrpSession wrpsession = new WrpSession();
wrpsession = (WrpSession) session.getAttribute("totalObj");
try {
List<EntFlatIncome> unitChargesList = new ArrayList<>();
unitChargesList = serbilldetails.doFetchManualChargesList(chargeid,wrpsession);
response.setStatus("success");
response.setDataObj(unitChargesList);
}
catch (Exception e){
e.printStackTrace();
response.setStatus("failed");
}
return response;
}
var app = angular.module('ngapppmanual', []);
app.controller('ngctrlmanual', function($scope, $http, $location) {
$scope.ngshowchargelist = false;
$scope.getChargeDetails = function()
{
var url = $location.absUrl() + "/showmanuallist/" + $scope.selectedcharge;
var config = {
headers : {
'Content-Type' : 'application/json;charset=utf-8;'
}
}
$http.get(url, config).then(function(response)
{
if (response.data.status == "success")
{
$scope.manualresult = response.data.dataObj;
$scope.ngshowchargelist = true;
} else
{
$scope.getResultMessage = "Customer Data Error!";
}
},
function(response)
{
$scope.getResultMessage = "Fail!";
});
}
});
I need to Load the Data in in same HTML page But the issue is while responding result as incl Error code 500
org.thymeleaf.exceptions.TemplateInputException: Error resolving template "manualbillentry/showmanuallist/1", template might not exist or might not be accessible by any of the configured Template Resolvers.
i cant understand the issue ,please someone helpme out...
you are using #Controller which returns html, instead you can use #RestController that returns JSON which angularJS is expecting
I am posting a form of type file and I am handling that POST request in spring-boot controller by returning JSON data. I checked that request with postman its working fine, But when I am using onreadystatechange method in react it is giving xhr status =0
onSubmitForm(){
console.log("entered");
var xhr = new XMLHttpRequest();
xhr.open('POST', '/images', true);
//xhr.responseType = 'text';
xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded');
var data = new FormData();
var imageFile = document.querySelector('input[type="file"]').files[0];
console.log( imageFile);
data.append("imageFile", imageFile);
xhr.onreadystatechange = function () {
if(xhr.readyState === XMLHttpRequest.DONE ){
alert(xhr.status);
if(xhr.status === 200){
alert('hi there');
}
}
}
xhr.send( data );
}
render() {
return (
<div>
<form encType="multipart/form-data" action="">
File to upload:
<input type="file" name="imageFile" accept="image/*" />
<input type="submit" value="Upload" onClick={ this.onSubmitForm.bind(this) } />
</form>
</div>
)
}
I am receiving the correct data in controller, But I am not getting JSON from POST request ??
controller
#PostMapping("/images")
public #ResponseBody JSONModel addContent( #RequestParam("imageFile") MultipartFile file,
imageApp content ) {
String encodedfile = null ;
double fileSize = file.getSize();
try {
byte[] bytes=file.getBytes();
System.out.println(fileSize/(1024*1024));
encodedfile = Base64.getMimeEncoder().encodeToString(bytes);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
content.setDate(LocalDateTime.now());
content.setLocation(UUID.randomUUID().toString() );
content.setId(UUID.randomUUID().toString() );
content.setContent(encodedfile);
return service.addContent(content);
}
service
public #ResponseBody JSONModel addContent(imageApp content) {
return new JSONModel(1, respository.save(content).getLocation());
}
Make <input type="submit" to type="button", keeping type="submit" tells the browser that page/form has to be submitted and it causing conflicting behavior which we need to prevent. So either change the type="button" or you can prevent the default behavior by taking the event in your handler and calling e.preventDefault();
HTML code:
<form id="pdfForm" class="display-inline" method="POST" action="{{document.PdfActionUrl}}">
<button uib-tooltip="Download PDF" type="submit" ng-disabled="document.CaseStudies.length == 0" class="uui-button button-action"><span class="icons-action icon-action-load"></span></button>
</form>
AngularJS code:
$scope.jsonToDoc = function (doc) {
document.PdfActionUrl = '/odata/DocumentsApi(' + document.Id + ')/API.DownloadPdf';
The server side code:
public HttpResponseMessage DownloadPdf([FromODataUri] Guid key)
{
var document = _documentService.GetPdfDocument(key, Request.RequestUri.BaseUri(System.Configuration.ConfigurationManager.AppSettings["setting"]));
HttpResponseMessage response = new HttpResponseMessage();
response.Content = new StreamContent(document.Content);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = document.Name
};
return response;
}
I'm not sure what approach best fits to this case and how to calculate downloading real time.
here is my all code i am trying to upload small image and large image separate but angularjs not let me allow to do this, it only taking one file but not taking other one. plz anyone help with this. thanks in advance.
<div ng-app="eventModule" >
<div ng-controller="eventController">
<div>
<span >Thumbnail Image</span>
<input type="file" id="fileToUpload" onchange="angular.element(this).scope().selectThumbnail(this.files)" accept="image/*" />
</div>
<div>
<span >Large Image</span>
<input type="file" onchange="angular.element(this).scope().selectLargeImage(this.files)" class="LargeImageSubCategory" />
</div>
</div>
<span data-ng-click="SaveFile()">Submit</span>
</div>
<script>
var eventModule = angular.module('eventModule', []);
eventModule.controller('eventController', function ($scope,ArticleService, $http, $sce) {
$scope.selectThumbnail = function (file) {
$scope.SelectedThumbnail = file[0];
}
$scope.selectLargeImage = function (file) {
$scope.SelectedLargeImage = file[0];
}
$scope.SaveFile = function () {
$scope.IsFormSubmitted = true;
$scope.Message = "";
ArticleService.UploadFile($scope.SelectedThumbnail, $scope.SelectedLargeImage).then(function (d) {
alert(d.Message);
ClearForm();
}, function (e) {
alert(e);
});
};
});
eventModule.service("ArticleService", function ($http, $q) {
this.UploadFile = function (Thumbnail, LargeImage, TitleHeading, Topic, SmallDesc, LargeDesc) {
var formData = new FormData();
formData.append("Thumbnail", Thumbnail);
formData.append("LargeImage", LargeImage);
// here when i am trying to send two files so controller is not called
//and function is breaking and alert is comming "File Upload Failed"
formData.append("TitleHeading", TitleHeading);
formData.append("Topic", Topic);
var defer = $q.defer();
$http.post("/Articles/SaveFiles", formData,
{
withCredentials: true,
headers: { 'Content-Type': undefined },
transformRequest: angular.identity
}).success(function (d) {
defer.resolve(d);
}).error(function () {
defer.reject("File Upload Failed!");
});
return defer.promise;
}
});
</script>
//And My ArticlesController.cs code is
[HttpPost]
public JsonResult SaveFiles(string TitleHeading, string Topic)
{
string Message, fileName, actualFileName;
Message = fileName = actualFileName = string.Empty;
bool flag = false;
if (Request.Files != null)
{
var file = Request.Files[0];
actualFileName = file.FileName;
fileName = Guid.NewGuid() + Path.GetExtension(file.FileName);
int size = file.ContentLength;
try
{
file.SaveAs(Path.Combine(Server.MapPath("~/UploadedFiles"), fileName));
using (TCDataClassesDataContext dc = new TCDataClassesDataContext())
{
Article insert = new Article();
insert.ArticleId = Guid.NewGuid();
insert.TitleHeading = TitleHeading;
insert.SmallImagePath = fileName;
dc.Articles.InsertOnSubmit(insert);
dc.SubmitChanges();
Message = "File uploaded successfully";
flag = true;
}
}
catch (Exception)
{
Message = "File upload failed! Please try again";
}}
return new JsonResult { Data = new { Message = Message, Status = flag } };
}
You are appending the files to the formdata, thus you need to specify the Thumbnail and LargeImage as parameters of your MVC controller. Please see below:
[HttpPost]
public JsonResult SaveFiles(
HttpPostedFileBase thumbnail
, HttpPostedFileBase largeImage
, string titleHeading
, string topic)
{
string Message, fileName, actualFileName;
Message = fileName = actualFileName = string.Empty;
bool flag = false;
if (thumbnail != null && thumbnail.ContentLength != 0)
{
SaveFile(thumbnail);
}
if (largeImage != null && largeImage.ContentLength != 0)
{
SaveFile(largeImage);
}
return new JsonResult { Data = new { Message = Message, Status = flag } };
}
private void SaveFile(
HttpPostedFileBase httpFile)
{
var actualFileName = httpFile.FileName;
var fileName = Guid.NewGuid() + Path.GetExtension(httpFile.FileName);
int size = httpFile.ContentLength;
try
{
httpFile.SaveAs(Path.Combine(Server.MapPath("~/UploadedFiles"), fileName));
using (TCDataClassesDataContext dc = new TCDataClassesDataContext())
{
Article insert = new Article();
insert.ArticleId = Guid.NewGuid();
insert.TitleHeading = TitleHeading;
insert.SmallImagePath = fileName;
dc.Articles.InsertOnSubmit(insert);
dc.SubmitChanges();
Message = "File uploaded successfully";
flag = true;
}
}
catch (Exception)
{
Message = "File upload failed! Please try again";
}
}
This is part of my servlet:
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
#SuppressWarnings("deprecation")
Map<String, BlobKey> blobs = blobstoreService.getUploadedBlobs(req);
UserService userService = UserServiceFactory.getUserService();
User user = userService.getCurrentUser();
ServletFileUpload upload = new ServletFileUpload();
FileItemIterator iterator;
try {
iterator = upload.getItemIterator(req);
Picture pic = null;
PictureAccess access = null;
while(iterator.hasNext()){
FileItemStream item = iterator.next();
pic = new Picture( blobs.get(item.getFieldName()).getKeyString() );
access = new PictureAccess();
access.addPictures(pic, user.getEmail() );
}
} catch (FileUploadException e) {
e.printStackTrace();
}
res.sendRedirect("/user/picture/upload.jsp");
}
In my client side, I used JavaScript to change the names of the file:
<script type="text/javascript">
function uploadFile() {
if (window.File && window.FileList) {
var fd = new FormData();
var files = document.getElementById('fileToUpload').files;
for ( var i = 0; i < files.length; i++) {
fd.append("file" + i, files[i]);
}
var xhr = new XMLHttpRequest();
xhr.open("POST", document.getElementById('uploadForm').action);
xhr.send(fd);
alert('already saved');
document.getElementById('uploadForm').value = '';
} else {
document.getElementById('uploadForm').submit(); //no html5
}
}
</script>
In my html/jsp:
<form id="uploadForm" enctype="multipart/form-data" method="post" action="<%= blobstoreService.createUploadUrl("/user/uploadPics") %>">
<input type="file" name="fileToUpload" id="fileToUpload" multiple="multiple" size="5"/>
<input type="button" onclick="uploadFile();" value="Upload" />
</form>
The above codes works in development machine but not working when deployed. What are the possible error and solution to the problem? How can I see the error in appengine?
Deprecated method getUploadedBlobs(..) does not support multiple='true'. Try using getUploads(..) instead.