Image upload using angularjs and servlet - java

I am trying to upload an image from html --> angularjs --> servlet --> database (here am using the post method).
My html is
<form class="formCls" ng-submit="addTravel()">
<input type="text" placeholder="Title" ng-model="travel.title"><br>
<input type="text" placeholder="Place from" ng-model="travel.from"><br>
<input type="text" placeholder="Place To" ng-model="travel.to"><br>
<input type="text" placeholder="With" ng-model="travel.withFrnd"><br>
<input type="file" ng-model-instant onchange="angular.element(this).scope().imageUpload(this)"><br>
<input type="submit" id="formSubmit" value="Submit">
<input type="reset" value="Reset"><br><br>
</form>
and my app.js is
$scope.imageUpload = function(element) {
var reader = new FileReader();
reader.onload = $scope.imageIsLoaded;
reader.readAsDataURL(element.files[0]);
}
$scope.imageIsLoaded = function(e) {
$scope.$apply(function() {
$scope.stepsModel.push(e.target.result);
});
}
$scope.addTravel = function() {
alert($scope.travel);
console.log($scope.stepsModel);
$http({
method : 'POST',
url : 'NewTravel',
headers : {
'Content-Type' : undefined
},
params : {
title : $scope.travel.title,
from : $scope.travel.from,
to : $scope.travel.to,
withFriend : $scope.travel.withFrnd,
imageArray : $scope.stepsModel
}
}).success(function(data, status, headers, config) {
console.log("I am done");
console.log("data " + data);
console.log(status);
console.log(headers);
console.log(config);
$scope.uploaded = 'uploaded Successfully';
$scope.travel = {};
somethingChanged = false;
}).error(function(data, status, headers, config) {
console.log("You need to nail me");
$scope.uploaded = 'Sorry';
});
}
and in servlet am getting it as
#Override
protected void service(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
System.out.println("I came to servlet");
System.out.println("Image Array"+request.getParameterValues("imageArray"));
String tvTitle = request.getParameter("title");
String tvFrom = request.getParameter("from");
String tvTo = request.getParameter("to");
String tvWith = request.getParameter("withFriend");
String tvImage = request.getParameterValues("imageArray");
System.out.println(tvTitle+"\n"+tvFrom+"\n"+tvTo+"\n"+tvWith+"\n"+tvImage);
}
}
if i do like this am not able to get the data at in the server side, am getting the error as con_Aborted or 400 bad request.
how do I upload an image and how do i get that image in the servlet. is that correct way of getting the image in servlet

Related

Handle Ajax sucess and error in jsp

I have Form in JSP which have two input boxes along with submit and clear button like this
<form name="loginForm" method="GET" action="Ajaxexample" id="loginForm">
<table>
<tr>
<td>From Date</td><td><input type="text" name="n1" value=""/></td>
</tr>
<tr>
<td>End Date</td><td><input type="text" name="n2" value=""/></td>
</tr>
<tr></tr>
<tr>
<td><input type="submit" name="validpro_insert" value="Insert"></td>
<td><input type="reset" name="validpro_clear" value="Clear"></td>
</tr>
</table>
</form>
As I have called the servlet using get method in form tag which is used to get data from database via JDBC API and to handle the response I have use ajax like this
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
System.out.println("In get");
PrintWriter out = response.getWriter();
String responseStr = "";
responseStr = addUser(request); // Return either error/success
System.out.println("Reponse:" + responseStr);
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
response.getWriter().write(responseStr);
out.print(responseStr);
As I have to write some code to get data from DB in servlet and return that response to ajax which handle success and error on the same jsp like this
<script type="text/javascript" src="js/jq.js"></script>
<script type="text/javascript">
var form = $('#loginForm');
form.submit(function () {
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize(),
error: function (theRequest,textStatus, errorThrown) {
// Success = false;
alert (theRequest.responseText);
alert(errorThrown);
alert('No graph found');//doesnt goes here
},
success: function (data) {
var result=data;
alert(result);
}
});
return false;
});
</script>
But the problem is that I am not getting any value from servlet in ajax to handle success or error
I think I am facing this problem due to servlet doget() method code.. if there is any other problem plz let me know. Any help should be appreciated
with these changes in my code, it runs successfully
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter())
String responseSend = "";
String from = request.getParameter("n1");
String to = request.getParameter("n2");
if ((from == null) || (from.equals(""))) {
System.out.println("From null");
responseSend = "error";
}
else if ((to == null) || (to.equals(""))) {
System.out.println("End null");
responseSend = "error";
}
else{
//jdbc code
System.out.println("got it");
int n1 = Integer.parseInt(request.getParameter("n1"));
int n2 = Integer.parseInt(request.getParameter("n2"));
responseSend = "code";
}
out.print(responseSend);
}
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("In get");
processRequest(request, response);
}
As I have added a new method processrequest() with request and response parameters which will return the text/HTML to our Ajax code on the same jsp.Firstly I am confused with success/error in ajax code but now I have found that
error: function (theRequest,textStatus, errorThrown) {
alert (theRequest.responseText);
alert(errorThrown);
},
success: function (data) {
var result=data;
alert(result);
}
The error will be called when it doesn't found servlet at given URL and success will be called when it successfully call the servlet with given type and servlet URL.
I have pasted my code here that work well
Try changing your parameter
Your JSP Page
<script src="http://code.jquery.com/jquery-1.10.2.js"
type="text/javascript"></script>
<form id="form">
Enter Your Name: <input type="text" id="userName" />
</form>
<br>
<br>
<strong>Ajax Response</strong>:
<div id="ajaxGetUserServletResponse"></div>
here is your ajax
$(document).ready(function() {
$('#form').submit(function() {
$.ajax({
url : 'GetUserServlet',
data : {
userName : $('#userName').val()
},
success : function(responseText) {
$('#ajaxGetUserServletResponse').text(responseText);
}
});
});
});
your servlet file
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class GetUserServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String userName = request.getParameter("userName").trim();
if(userName == null || "".equals(userName)){
userName = "Guest";
}
String greetings = "Hello " + userName;
response.setContentType("text/plain");
response.getWriter().write(greetings);
}
}

How to upload form with image file in it, AngularJS spring

I have this form
<div class="row">
<h1 class="page-header">
Create
</h1>
<form ng-submit="create()", enctype="multipart/form-data">
<div class="form-group">
<label>Name:</label>
<input type="text" ng-model="subforum.name" class="form-control" />
</div>
<div class="form-group">
<label>Desc:</label>
<input type="text" ng-model="subforum.desc" class="form-control" />
</div>
<input type="file" ngf-select ng-model="subforum.icon" name="subforum.icon"
accept="image/*" ngf-max-size="2MB" required
ngf-model-invalid="errorFile">
<img ng-show="myForm.file.$valid" ngf-thumbnail="subforum.icon" class="thumb"> <button ng-click="subforum.icon= null" ng-show="subforum.icon">Remove</button>
<button class="btn btn-success" type="submit">Create</button>
</form>
``
In my JS
.config(function($stateProvider) {
$stateProvider.state('create', {
url:'/subforum/create',
views: {
'main': {
templateUrl:'subforum/create.tpl.html',
controller: 'CreateCtrl'
}
},
data : { pageTitle : "Create Subforum" }
})
and
.factory('subforumService', function($resource) {
var service = {};
service.create = function (subforum, success, failure) {
var SubForum= $resource ("/web-prog/rest/subforums");
SubForum.save({}, subforum, success, failure) ;
};
.controller("CreateCtrl", function($scope, $state, subforumService) {
$scope.create = function() {
$scope.subforum.author = JSON.parse(localStorage.getItem ("logedUser"));
subforumService.create($scope.subforum,
function(returnedData) {
$state.go("home");
},
function() {
alert("Error creating");
});
};
I know thats not best practice to save user in LocalStorage but for now its like that.
On backend i have controller and in that controller i have methode:
#RequestMapping(method = RequestMethod.POST)
public ResponseEntity<SubForumResource> createPodforum(#RequestBody SubForumResource sentPodforum) {
}
and SubForumResource is
public class PodforumResource extends ResourceSupport {
private String name;
private String desc;
private byte[] icon;}
with geters and seters and everything i need.
So when i have form without image it works without problems. But i need icon too. Im new to angularjs but need it for this project. When i try to use FormData() i dont know how to use $resource. So if someone can help me i would be thankful. This is my first prject i need to work front end so im lost.
You can refer below code for angularjs :
this.addEmployee = function (requestData, file) {
var data = new FormData();
data.append('file', file[0]);
data.append('requestData', new Blob([JSON.stringify(requestData)], {
type: "application/json"
}));
var config = {
transformRequest: angular.identity,
transformResponse: angular.identity,
headers: {
'Content-Type': undefined
}
}
var url = "http://localhost:8080/addEmployee";
var promise1 = $http.post(url, data, config);
var promise2 = promise1.then(function (response) {
return response.data;
},
function errorCallback(response) {
alert(response.data.errorMessage);
});
return promise2;
}
And for controller :
#RequestMapping(value = "/addEmployee", method = RequestMethod.POST, consumes = {"multipart/form-data" })
#CrossOrigin
public CustomResponse addEmployee(#RequestPart("file") MultipartFile file, #RequestPart("requestData") Employee emp) {
}

AngularJS post method not working

I went through lots of stack overflow and google stuffs i don't know where am missing the url every time am getting the error as 404 for the controller file
my jsp is
<div id="signUp" class="signUp" >
<form class="formCls" method="POST" ng-submit="createUser()">
<input type="text" placeholder="Name" ng-model="signUp.name"><br>
<input type="email" placeholder="Email" ng-model="signUp.email"><br>
<input type="date" placeholder="dateOfBirth" ng-model="signUp.dob"><br>
<input type="password" placeholder="Password" ng-model="signUp.password"><br>
<input type="password" placeholder="Conform Password"><br>
<input type="submit" value="Login">
<input type="reset" value="Reset"><br><br>
To Login Click Here
</form>
</div>
my app.js is
myApp.controller('myControler', function($scope, $http) {
$scope.createUser = function() {
alert("hai");
console.log($scope.signUp);
$http({
method : 'POST',
url : 'http://localhost:8080/travelBlog/src/com/bluewind/ccontroller/Signup',
headers: {'Content-Type': 'application/json'},
data : '$scope.signUp'
}).success(function (data){
console.log("I am done");
$scope.myWelcome = data;
});
};
});
my servlet program is
#WebServlet("/Signup")
public class Signup extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
#Override
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("I came to servlet");
String memberName = request.getParameter("signUp.name");
System.out.println(memberName);
}
}

How to check if form was submitted in Java

I have a form in jsp:
<form id="emailForm" data-role="form">
<input type="text" class="form-control" id="name" name="name" placeholder="Enter full name..">
<input type="submit" id="emailSubmit" name="emailSubmit" class="btn btn-default" value="submit">
</form>
I send the form to controller using AJAX:
$("#emailSubmit").click(function(e){
e.preventDefault(); //STOP default action
var postData = $("#emailForm").serializeArray();
$.ajax(
{
type: "POST",
url : "HomeController",
data : postData,
success: function(data)
{
$("#emailResult").html("<p>Thank your for submitting</p>);
},
error: function(jqXHR, textStatus, errorThrown)
{
$("#emailResult").html("<p>ss"+errorThrown+textStatus+jqXHR+"</p>");
}
});
});
I check if it has been submitted in Controller here:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String emailSubmit = request.getParameter("emailSubmit");
if(emailSubmit != null){
// continue
}}
Can someone please tell me why when it checks if form was submitted in the controller that it is null?
For forms the standard way is to catch the submit event instead of the click event of the button:
$("#emailForm").submit(function(e){
e.preventDefault();
var postData = $(this).serializeArray(); // or: $(this).serialize();
$.ajax({
type: "POST",
url : "HomeController",
data : postData,
success: function(data)
{
$("#emailResult").html("<p>Thank your for submitting</p>);
},
error: function(jqXHR, textStatus, errorThrown)
{
$("#emailResult").html("<p>ss"+errorThrown+textStatus+jqXHR+"</p>");
}
});
});
I have tried several methods to be able to check the submit button isn't null and can't solve that issue. For now I have set a hidden input field in the form like so:
<input type="hidden" name="form" value="contactForm">
In controller I check for the form:
String form = request.getParameter("form");
if(form.equals("contactForm")){
// continue
}
Doing this enables me to know which form has been posted to the controller.

Uploading large files with HttpClient

I want to upload large video files (>=1Gb) with HttpClient to a servlet but I couldn't find any real examples.
Could you give me some useful code examples?
I'd like to see both the HttpClient and FileUpload demo codes (as a one project). And it is quite interesting can I use FileUpload lib to download large files?
It is interesting to have upload bound like this applet -> servlet
Here's an example of HttpClient and file upload:
http://www.theserverside.com/news/1365153/HttpClient-and-FileUpload
I'm not sure that you mean by "real". It's real enough, even if it doesn't precisely match your situation.
1GB? You're likely to have file size limitation issues. Try it locally and see. If it fails, at least you'll have some real code and more exact conditions to post here.
I am able to upload large files >200mb , Please look into below jsp to spring controller code .
Jsp code :
<script src="../lib/app/configurator.data.ajax.js" type="text/javascript"></script>
<script src="../lib/ui/jquery.fileupload.js"></script>
<html>
<script language="Javascript">
var varb = '';
var test = 0;
var count = 1;
$(function () {
var maxChunkSize = 30000000; //SET CHUNK SIZE HERE
var your_global_var_for_form_submit = '';
var params = {
year: threeDSelectedYear,
series: threeDSelectedSeries
};
/*File upload bind with form, 'fileupload' is my form id. As sumit triggers
for file ulaod will submit my form*/
/* replaceFileInput: true, */
$('#fileupload').fileupload({
maxChunkSize: maxChunkSize,
url: efccustom.getEfcContext()+'upload/uploadZip?year='+threeDSelectedYear+'&series='+threeDSelectedSeries, //URL WHERE FILE TO BE UPLOADED
error: function (jqXHR, textStatus, errorThrown) {
// Called for each failed chunk upload
$(".fileupload-loading").html("");
$('.ANALYZE_DIALOG').dialog("close");
},
success: function (data, textStatus, jqXHR) {
/*This event will be called on success of upload*/
count = parseInt($('#counter').val()) + 1;
$('#counter').val(count);
$('#ttk').val(count);
data.ttk = 7;
console.log(" count ",count , data);
},
submit: function (e, data) {
/*This event will be called on submit here i am
adding variable to form*/
//console.log($('#zip_uploaded_file').val());
//console.log(data.originalFiles[0].name);
test = data.originalFiles[0];
$('#fname').val(data.originalFiles[0].name);
$('#trequests').val(Math.ceil(data.originalFiles[0].size/maxChunkSize));
$('#counter').val('1');
},
progress: function (e, data) {
/*PROGRESS BAR CODE WILL BE HERE */
$(".fileupload-loading").html('<img src="../public/themeroller/images/throbber.gif" alt="Uploading Please Wait..." title="Uploading Please Wait...." />');
},
add: function (e, data) {
$('.browsedFileName').html(data.originalFiles[0].name);
your_global_var_for_form_submit = data;
},
done: function (e, data) {
ajaxcall.Data._get('upload/extractZipNCreateJson',params,function(data2) {
alert("file upload success ");
$(".fileupload-loading").html("");
$('.ANALYZE_DIALOG').dialog("close");
});
}
});
/*This is my button click event on which i am submitting my form*/
$('#button').click(function(){
your_global_var_for_form_submit.submit();
});
});
</script>
<html>
<body>
<form id="fileupload" enctype="multipart/form-data">
<div class="row fileupload-buttonbar">
<div class="span7">
<!--<input type="file" name="files" id="file" /> -->
<input type="file" id="zip_uploaded_file" name="zip_uploaded_file" />
<input type="hidden" name="counter" id="counter" value="1" />
<input type="hidden" name="fname" id="fname" value="" />
<input type="hidden" name="trequests" id="trequests" value="1" />
<input type="hidden" name="ttk" id="ttk" value="1" />
<input type="button" id="button" name="button" value="submit" />
<span class='browsedFileName'></span>
</div>
</div>
<!-- The loading indicator is shown during file processing -->
<div class="fileupload-loading"></div>
</form>
</body>
Controller COde :
#RequestMapping(value = "/uploadZip", method = RequestMethod.POST, consumes = "multipart/form-data")
#ResponseBody
public ResponseEntity<String>
uploadZip(HttpServletRequest request, HttpServletResponse response)
throws IOException, IllegalArgumentException {
try {
String year = request.getParameter("year");
String series = request.getParameter("series");
log.info(" year " + year + " series " + series);
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart) {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List items = upload.parseRequest(request);
Iterator iterator = items.iterator();
HttpSession session = request.getSession();
UserContext userContext = (UserContext) session
.getAttribute(ApplicationConstant.USER_CONTEXT);
String userName = userContext.getUser();
String workSpaceInUse = userContext.getCurrentWorkSpace();
FileItem item = null;
boolean fileNotExistFlag;
String fileExtension;
while (iterator.hasNext()) {
item = (FileItem) iterator.next();
String content = item.getContentType();
log.info(" content "+content);
log.info(" File Type Getting Uploaded :"+content);
if (!item.isFormField()) {
/* Here in IOUtils the Third Parameter true tells that the small chunks of data that comes need to be added to the same File */
IOUtils.copy(fileItem.getInputStream(), new FileOutputStream(new File(threeDPath+"/"+year+"/"+series+"/"+uploadZipFileName),true));
}
}
return null;
}
}
catch(Exception e) {
return handleError(new RuntimeException("Unexpected error while uploading ZIP", e));
}
return null;
}

Categories