Upload cropped "croppie" image to server using Java PlayFramework 2.6 - java

I've googled for the past 2 days and still can't find a solution to this problem. I can upload fine using the input element with type attribute set to file. But I cannot upload the cropped image using croppie to the server.
Here is my register.scala.html:
#helper.form(action = routes.ProfilesController.upload, 'id -> "profileForm", 'class -> "", 'enctype -> "multipart/form-data") {
#CSRF.formField
<div class="col-6 col-md-3 pic-padding">
<div id="upload-demo" class="upload-demo pic-1 mx-auto d-block rounded">
</div>
<div class="pic-number" href="#">1</div>
<label for="upload-pic1" class="pic-control-bg">
<img src="#routes.Assets.versioned("images/plus.png")" class="pic-control">
</label>
<input type="file" id="upload-pic1" name="pic1" class="upload-btn" accept="image/*">
<button type="button" class="upload-result">Result</button>
<script>
Demo.init();
</script>
</div>
}
Here is my main.js:
$('.upload-result').on('click', function (ev) {
$uploadCrop.croppie('result', {
type: 'canvas',
size: 'viewport'
}).then(function (resp) {
$.ajax({
url: "http://localhost:9000/upload",
type: "POST",
data: {"image":resp},
success: function (data) {
alert(resp);
}
});
});
});
Here is my ProfilesController.java
public Result upload() {
File file = request().body().asRaw().asFile();
return ok("File uploaded");
}
Here is a snippet from routes file:
POST /upload controllers.ProfilesController.upload()
The error i get with the above solution is:
[CompletionException: java.lang.NullPointerException]
Please help! This has been stressing me out for the past 2 days, I just can't figure it out.

This is not fully solved, but i've progressed enough to produce a different problem. I ended up changing my ajax request in main.js to:
$.ajax({
url: "http://localhost:9000/upload",
type: "POST",
data: resp,
success: function (data) {
alert(resp);
Then I also changed the profilecontroller.java to
public Result upload() {
String dataUrl = request().body().asText();
System.out.println(dataUrl);
return ok("Data URI Passed");
}
This gave me the Data URI from javascript and passed it to the JAVA code. Now I need to try and upload the image using the Data URI. If you know the answer to this then please contribute to this post.

Related

when I pass html form data to local java spark server (main.java) the jquery can't find the url

I need help passing some form data to main.java server (I am using java spark) using jquery
the server takes data from the url, so I want to send the data in the url
<button type="submit" id="btn" class="btn btn-primary">submit</button>
<script> $(document).ready(function () {
$('#btn').click(function () {
var firstVar = $('#var1').val();
var secondVar = $('#Var2').val();
$.ajax({
url:"/variabless",
url: "/Variables/:Var1=firstVar&Var2=secondVar",
success: function (result) {
alert('success');
},
/* error: function (err) {
alert("fail");
}*/
});

Can't Pass MultipartFile through Ajax JAVA [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I'm trying to send a file from my jsp to controller via ajax, im getting EXCEPTION:Null Error, below is my code:
Controller:
#RequestMapping(value = "/schedulebatch",method =
RequestMethod.POST,params="insertData")
public #ResponseBody String addBatch(#RequestParam(
#RequestParam(value="upfile",required=false) MultipartFile upfile) throws
Exception { if(!upfile.isEmpty()){
System.out.println("test1");}
View:
$("#submit-btn").click(function(){
var upfile = document.getElementById('upfile').enctypeVIEW;
alert('test');
if(batchname==null || fromdate == null || partners == null || interval ==
null){
$('#insertmodalalert').empty();
$('#insertmodalalert').append('<div class="alert alert-info"><strong
>NOTICE |</strong> Please fill out the required form. </div>');
$('#alertMod').modal();
$('#okbtn').click(function(){
window.location.reload(true);
});
}
else{
$.ajax({
type: "POST",
url: "schedulebatch?insertData",
data: {"upfile" : upfile},
success: function(response){
// alert('test');
$('#insertmodalalert').empty();
$('#insertmodalalert').append('<div class="alert alert-
info"><strong >NOTICE |</strong> '+response+' </div>');
$('#alertMod').modal();
$('#okbtn').click(function(){
$('#alertMod').modal('hide');
window.location.reload(true);
});
},
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
// alert('test');
// Display the specific error raised by the server
(e.g. not a
// valid value for Int32, or attempted to divide by
zero).
$('#insertmodalalert').append('<div class="alert
alert-danger"><strong >NOTICE |</strong> '+err.Message+'</div>');
$('#activateMod').modal();
$('#okbtn').click(function(){
$('#alertMod').modal('hide');
window.location.reload(true);
});
}
});
//alert("Test");
}
HTML:
File to upload: <input class="form-control" type="file" name="upfile"
accept=".csv" id="upfile">
<button type="submit" class="btn btn-success" id="submit-
btn">Submit</button>
I narrowed down the code to the only thing that gives me error, thanks in advance. It gets the Multipart file successfully but im not sure why it gives a null exception error
When I uploading files with my RestController in Spring Boot I used like below and everything is fine :
#PostMapping
public ResponseEntity<User> post(UserCreateRequest request, #RequestPart("file") MultipartFile file) throws IOException {
ftpService.uploadPhoto(file.getOriginalFilename(), file.getInputStream());
return ResponseEntity.ok(userService.create(request));
}
So may be you can try to change your code as below:
#RequestMapping(value = "/schedulebatch",method =
RequestMethod.POST,params="insertData")
public #ResponseBody String addBatch(#RequestPart("upfile") MultipartFile upfile) throws Exception {
if(!upfile.isEmpty()){
System.out.println("test1");
}
}
And your content-type should be multipart/form-data so I added an example html&ajax form request:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script>
$(document).ready(function () {
$('#btnSubmit').click( function(e) {
e.preventDefault();
var form = $('#my-form')[0];
var data = new FormData(form);
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
url: "http://localhost:8080/schedulebatch",
data: data,
processData: false,
contentType: false,
cache: false,
timeout: 600000,
success: function (data) {
alert("success")
},
error: function (e) {
alert("ERROR : ", e);
}
});
});
});
</script>
</head>
<body>
<form method="POST" enctype="multipart/form-data" id="my-form">
<input type="file" name="upfile"/><br/><br/>
<input type="submit" value="Submit" id="btnSubmit"/>
</form>
</body>
</html>

Example of AJAX Request on PHP?

I am new to AJAX Request, and my project need help.
JQuery / AJAX part :
<script>
$(document).ready(function(){
$("button").click(function(){
$.ajax({
type: 'POST',
url: 'ajax_save.php',]
success: function(msg) {
alert(msg);
}
error: function(msg) {
alert('error');
}
});
});
});
</script>
html part :
<input type="text" id="txt" name="text" />
<span id="txt">Result Maybe Here</span>
<button>Get External Content</button>
ajax_save.php
echo base64_encode( $_GET["text"] );
This don't really perform well, and just silent with out any trace.
Example of performing well :
<input type="text" id="txt" name="text" /> >>> agnes (user type)
<span id="txt">Result Maybe Here</span> >>> YWduZXM= (result)
<button>Get External Content</button>
About Ajax
To perform AJAX request on browser(client side), you need JavaScript. Maybe you can take a look at jQuery.ajax. $.get('process.php?text=something');
To perform AJAX request in PHP(server side), use file_get_contents('process.php?text=something');
To make your code work, you should perform a GET request instead of a POST one:
<script>
$(document).ready(function(){
$("button").click(function(){
$.ajax({
type: 'GET',
url: 'ajax_save.php?text=' + $('#text').val(),
success: function(msg) {
$('#span').text(msg)
}
error: function(msg) {
alert('error');
}
});
});
});
</script>
And every id in your HTML element should be unique, so they shouldn't both be id="txt".
About Base64
BTW, if you're just going to perform Base64 encoding, why not do it in JavaScript?
$(function(){
$('#text').on('input', function(){
$('#span').text(btoa($(this).val()));
});
});
<input type="text" id="text" name="text" />
<span id="span">Here the result!</span>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Communicate with backend method through Ajax

I am trying to communicate with a method using Ajax and AngularJS but I'm not getting a response and the alert outputs undefined.
Index.cshtml
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body ng-app="myApp">
// Displaying the table is working
<div>
<table class="table" ng-controller="UpdateController">
<tr>
<th>Id</th>
<th>Name</th>
<th>Country</th>
</tr>
<tr ng-repeat="c in cities">
<td>{{c.Id}}</td>
<td>{{c.City1}}</td>
<td>{{c.Country}}</td>
</tr>
</table>
</div>
// Here I add the controller for adding records -->
<div ng-controller="AddRecord">
<form id="form1" ng-submit="send()">
<table>
<tr>
<td>City: </td>
<td>
<input type="text" id="txtCity" ng-model="addCity" />
</td>
</tr>
<tr>
<td>Country: </td>
<td>
<input type="text" id="txtCountry" ng-model="addCountry" />
</td>
</tr>
<tr>
<td>
<input type="submit" id="btnSubmit" value="Submit" />
</td>
</tr>
</table>
</form>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('UpdateController', function ($scope, $http) {
$http.get("http://localhost:50366/api/cities")
.success(function (response) { $scope.cities = response });
});
app.controller('AddRecord', function ($scope, $http) {
// Function responsible for communicating with backend
$scope.send = function () {
$.ajax({
type: "POST",
url: "AddCity.asmx.cs/PostCity",
data: "{'city':'" + $scope.addCity + "','country':'" + $scope.addCountry + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg.d);
},
error: function (msg) {
alert(msg.d);
}
});
//Here is one I tried using text as the datatype:
$.ajax({
type: "POST",
url: "AddCity.asmx/PostCity",
data: "city=" + $scope.addCity + "&country=" + $scope.addCountry,
dataType: "text",
success: function (msg) {
alert(msg.d);
},
error: function (msg) {
alert(msg.d);
}
});
};
});
</script>
</body>
</html>
AddCity.asmx with the method I'm trying to access
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using AngularWebApi.Models;
using AngularWebApi.Controllers;
namespace AngularWebApi.Views
{
/// <summary>
/// Summary description for AddCity
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class AddCity : System.Web.Services.WebService
{
[WebMethod]
public string PostCity(string city, string country)
{
City newCity = new City();
newCity.City1 = city;
newCity.Country = country;
//Eventually I want to add the city to the database
CitiesController controller = new CitiesController();
controller.PostCity(newCity);
return "Posted!";
}
}
}
Index.cshtml resides in Views/Home and AddCity.asmx resides in Views. I tried to use url: "../AddCity.asmx/PostCity" as well.
Edit
I quickly created a new project and set it up, the exact same thing is happening, here are the steps:
New web api project
New ADO.net Entity data model and link it to my DB
New Web API 2 controller with actions using Entity Framework passing the table from DB and entity I got from pevious step.
Then I edit Index.cshtml to show the XML from API/CITIES as a table. This time I added my service in the root of the project and just trying to call the auto created HelloWorld with the $.ajax POST function.
I do see a warning in the FF error console. Literal translation from dutch: Cross-Origin-Request blocked: ....
Furthermore the error is triggered within the ajax call. The WebService is not being reached afaik.
This is the complete reply I get when I click the button:
<!DOCTYPE html>
<html>
<head>
<title>The resource cannot be found.</title>
<meta name="viewport" content="width=device-width" />
<style>
body {font-family:"Verdana";font-weight:normal;font-size: .7em;color:black;}
p {font-family:"Verdana";font-weight:normal;color:black;margin-top: -5px}
b {font-family:"Verdana";font-weight:bold;color:black;margin-top: -5px}
H1 { font-family:"Verdana";font-weight:normal;font-size:18pt;color:red }
H2 { font-family:"Verdana";font-weight:normal;font-size:14pt;color:maroon }
pre {font-family:"Consolas","Lucida Console",Monospace;font-size:11pt;margin:0;padding:0.5em;line-height:14pt}
.marker {font-weight: bold; color: black;text-decoration: none;}
.version {color: gray;}
.error {margin-bottom: 10px;}
.expandable { text-decoration:underline; font-weight:bold; color:navy; cursor:hand; }
#media screen and (max-width: 639px) {
pre { width: 440px; overflow: auto; white-space: pre-wrap; word-wrap: break-word; }
}
#media screen and (max-width: 479px) {
pre { width: 280px; }
}
</style>
</head>
<body bgcolor="white">
<span><H1>Server Error in '/' Application.<hr width=100% size=1 color=silver></H1>
<h2> <i>The resource cannot be found.</i> </h2></span>
<font face="Arial, Helvetica, Geneva, SunSans-Regular, sans-serif ">
<b> Description: </b>HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
<br><br>
<b> Requested URL: </b>/Home/MyWebService.asmx/HelloWorld<br><br>
<hr width=100% size=1 color=silver>
<b>Version Information:</b> Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.18408
</font>
</body>
</html>
<!--
[HttpException]: A public action method 'MyWebService.asmx' was not found on controller 'AngularTutorial.Controllers.HomeController'.
at System.Web.Mvc.Controller.HandleUnknownAction(String actionName)
at System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End()
at System.Web.Mvc.Async.AsyncResultWrapper.End[TResult](IAsyncResult asyncResult, Object tag)
at System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag)
at System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult)
at System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End()
at System.Web.Mvc.Async.AsyncResultWrapper.End[TResult](IAsyncResult asyncResult, Object tag)
at System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag)
at System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult)
at System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult)
at System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End()
at System.Web.Mvc.Async.AsyncResultWrapper.End[TResult](IAsyncResult asyncResult, Object tag)
at System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag)
at System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult)
at System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
-->
Edit
The POST method in the controller:
// POST: api/Cities
[ResponseType(typeof(City))]
public IHttpActionResult PostCity(City city)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
db.Cities.Add(city);
db.SaveChanges();
return CreatedAtRoute("DefaultApi", new { id = city.Id }, city);
}
hmmm, I think I got it: you try to create a new POST-Method, but according to the tutorial, there is already a POST-Method in the City-Controller:
By clicking on Add, we are able to create the Cities Web API using the scaffolding. The created controller class will have a Web API for all the CRUD operations on the city table.
that means you simply need to send your ajax-call to http://localhost:50366/api/cities:
$.ajax({
type: "POST",
url: "http://localhost:50366/api/cities",
data: "{'country':'" + country + "','name':'" + cityName + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg.d);
},
error: function (msg) {
alert(msg.d);
}
});
Make sure you only have 1 web application running, so you can avoid unnecessary problems.
btw. I'm not sure, if the controller will accept json maybe you need to send the data as xml...
EDIT:
I updated the json data. Your city-object has 3 properties: country, id and name. If you send a POST request you are about to create a new object, so you don't need to send the id.
For PUT and DELETE (if you want to implement this functions) you will need to add the idto the url:
http://localhost:50366/api/cities/:id
EDIT2:
ok, the xml should looks like this:
data: "<City><Country>" + country + "</Country><Name>" + cityName + "</Name></City>",
don't forget to change:
contentType: "application/xml; charset=utf-8",
dataType: "xml",
Don't use ajax, even if it worked you would still have problems because $.ajax calls are not in Angular.js context and you would have to manually $scope.apply() the returned value. Use angular $http service instead. You can find how to use it in official documentation. It is very flexible, supports all request methods, query params, request body, etc... also supports interceptors to handle all your requests. All $http calls return promise by default (also use .then() handler instead of success and failure handlers).

jQuery setting input field value

I have a form to edit user and i would like to insert user data from database into forms' fields. What i do is
Link
Edit
Script
function editUser(url) {
$( "#edit-form" ).dialog( "open" );
$.ajax({
url: url,
type: "POST",
success: function (resp) {
$('input[name="elogin"]').val(resp.login);
}
})
}
Form
<div id="edit-form" title="Edit user">
<p class="validateTips">All form fields are required.</p>
<form:form>
<fieldset>
<label for="elogin">Login</label>
<input type="text" name="elogin" id="elogin" class="text ui-widget-content ui-corner-all" />
</fieldset>
</form:form>
</div>
My Spring controller returns following(in wrapper i have field login)
#RequestMapping(value="/edit/{userLogin}", method=RequestMethod.POST)
#ResponseBody
public Wrapper edit(#PathVariable String userLogin) {
return wrapper.wrap(userService.findByLogin(userLogin));
}
But the form is empty. I also tried to set manual values but still no use. Please help me set input field value.
You should send your form data with your post request.
$.ajax({
url: url,
type: "POST",
data:$('form').serialize(),
success: function (resp) {
$('input[name="elogin"]').val(resp.login);
}
})
function editUser(url) {
$( "#edit-form" ).dialog( "open" );
$.ajax({
url: url,
type: "POST",
success: function (resp) {
$('#elogin').val(resp.login);
}
})
}
Should work just fine, as you've set an ID for the input.
Not quite sure you have the order right, surely you would make the ajax call first and then open up the jQuery dialog?
Either way, you could supply data into the dialog as follows;
//call ajax method to get value you want to show.
var somevariable = etc.....
var dto = {
loginName: somevariable
}
$( "#edit-form" ).data('params', dto).dialog( 'open' );
Then in your dialog use the open() method.
$("#edit-form").dialog({
bgiframe: true,
autoOpen: false,
height: 280,
width: 320,
draggable: false,
resizable: false,
modal: true,
open: function () {
//so values set in dialog remain available in postback form
$(this).parent().appendTo("form");
//get any data params that may have been supplied.
if ($(this).data('params') !== undefined) {
//stuff your data into the field
$("#elogin").val($(this).data('params').loginName);
}
}
});

Categories

Resources