Can't Pass MultipartFile through Ajax JAVA [duplicate] - java

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>

Related

MissingServletRequestPartException: Required request part file is not present using Ajax

I tried and tried too different approaches but my error is still same, It can not be resolved from my side. its showing
Resolved exception caused by Handler execution: org.springframework.web.multipart.support.MissingServletRequestPartException: Required request part file is not present
My jsp code is
<form name="upload_document_form" onsubmit="return false" enctype="multipart/form-data">
<input type="file" name="file"/>
<button class="btn btn-primary btn-lg" name="upload_document_form_btn" id="upload_document_form_btn" onclick="UploadDocuments()">Upload</button>
</form>
Ajax call function
function UploadDocuments(){
var formData = new FormData();
formData.append('file',$("#file").val());
$.ajax({
type: 'POST',
url: 'http://localhost:8080/insertDocumentData',
enctype: 'multipart/form-data',
data: formData,
type: 'POST',
dataType:'json',
contentType: false,
processData: false,
success: function(msg) {
}
});
}
Controller is
private static String UPLOAD_FOLDER = "uploaded_Doc/AP12345";
#PostMapping("/insertDocumentData")
public boolean insertDocumentData(#RequestParam("file") MultipartFile file,RedirectAttributes redirectAttributes) throws IOException{
if (file.isEmpty()) {
System.out.println("file is empty");
return false;
}
try {
byte[] bytes = file.getBytes();
Path path = Paths.get(UPLOAD_FOLDER +"/"+ file.getOriginalFilename());
Files.write(path, bytes);
} catch (IOException e) {
e.printStackTrace();
}
return true;
}

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

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.

Building Restful Web Service using Spark Java for Library Management System

I am new with Spark Java. I have made a Library Management System with get and post methods written in Java. I have made an HTML form that takes information of user and creates users which gets stored in a ArrayList of objects in Java. When I call get method to return the list of user objects created via ajax, nothing gets returned. Success nor error gives any output.
But when I simply put the url : http://localhost:4567/users
I get the following output:
[{"id":1,"firstName":"Bhavya","lastName":"Chauhan","age":"22","gender":"F","phone":"1234567890"},
{"id":2,"firstName":"Rashi","lastName":"Chauhan","age":"20","gender":"F","phone":"1233455677"}]
I have attached my html and Spark java code. Thanks in advance!
<!DOCTYPE html>
<html>
<head>
<title>Text Input Control</title>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<meta charset="utf-8"/>
</head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script type="text/javascript"></script>
<script>
$(function () {
$("#userGet").click(function(){
alert("Here");
$.ajax({
type: 'GET',
url: 'http://localhost:4567/users',
crossDomain: true,
data: '',
dataType: 'jsonp',
async:false,
success: function(responseData) {
//$("#divid").html(+responseData);
alert("hi");
},
error: function(jqXHR, exception) {
if (jqXHR.status === 0) {
alert('Not connect.\n Verify Network.');
} else if (jqXHR.status == 404) {
alert('Requested page not found. [404]');
} else if (jqXHR.status == 500) {
alert('Internal Server Error [500].');
} else if (exception === 'parsererror') {
alert('Requested JSON parse failed.');
} else if (exception === 'timeout') {
alert('Time out error.');
} else if (exception === 'abort') {
alert('Ajax request aborted.');
} else {
alert('Uncaught Error.\n' + jqXHR.responseText);
}
}
});
});
});
</script>
<body>
<h2>Library Management System </h2>
<button>Get Stuff</button>
<form>
<h3>Manage Users </h3>
<input type=button onClick="location='CreateUser.html'" value='Create User'>
<br><br>
<input type=submit id="userGet" value='Get All Users'>
<br><br>
<input type=button onClick="location='UpdateUser.html'" value='Update User'>
<br><br>
</form>
<form action="http://localhost:4567/books" method="GET">
<h3>Manage Books </h3>
<input type=submit value='Get All Books'>
<br><br>
<input type=button onClick="location='FindBookByName.html'" value='Find Book By Name'>
<br><br>
<input type=button onClick="location='AddBook.html'" value='Add Book'>
<br><br>
<input type=button onClick="location='CheckOutBook.html'" value='Check Out Book'>
<br><br>
</form>
<div id="divid"></div>
</body>
</html>
Here is the Java:
import static spark.Spark.*;
public class UserController extends JsonUtil
{
public UserController(final UserService userService)
{
System.out.println("in user controller");
get("/users", (req, res) -> userService.getAllUsers(), json());
get("/books", (req, res) -> userService.getAllBooks(), json());
post("/users", (req, res) -> userService.createUser(req.body()), json());
post("/users/:id", (req, res) -> userService.updateUser(req.body()),json());
post("/books", (req, res) -> userService.addBook(req.body()), json());
post("/books/:name", (req, res) -> userService.findBookByName(req.body()),json());
post("/checkedOut", (req, res) -> userService.checkOutBook(req.body()), json());
}
}

post comments using jsp, servlet and ajax

I am trying to create a comment section using jsp, servlet and ajax. The problem I am facing is that each comment replaces it's previous one instead of showing next to it.
Highly appreciate any kind of help.
<script type="text/javascript" src="js/jquery-1.11.3.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#submitBtn').click(function() {
var cmt = $('#cmt').val();
$.ajax({
type : 'POST',
data : {
cmt : cmt,
action : 'EnterMsg'
},
url : 'SubmitComment',
success : function(result) {
$('#view2').text(result);
}
});
});
});
</script>
</head>
<body>
<fieldset>
<legend>Enter Message</legend>
<form>
Ques.<input type="text" id="cmt"> <input type="button"
value="Send" id="submitBtn"><br> <span id="post1"></span>
</form>
</fieldset>
<fieldset>
<legend>View Message</legend>
<form>
<div id='view2'></div>
<br>
</form>
</fieldset>
Try
var html='';
$.ajax({
dataType: "json",
url: "SubmitComment",
error: function () {
alert('error occured');
},
success: function (result) {
for(var key in result) {
var value = result[key];
html+='<div>'+key+':'+value+'</div>'
}
$("#view2").append(html);
}
});
Instead of
success : function(result) {
$('#view2').text(result);
}
Because of you get multiple comments from the ajax respose and you have to iterate each one of them and append to your div tag

java.io.EOFException: No content to map to Object due to end of input Spring MVC Jackson Processor

I am using Spring MVC and JSP to send JSON to Spring MVC Controller. Actually, my JSON works for 1 method but does not work for another and I don't understand why. The code is below:
JSP - index.jsp
<%#page language="java" contentType="text/html"%>
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$('#myForm').submit(function() {
var form = $( this ),
url = form.attr('action'),
userId = form.find('input[name="userId"]').val(),
dat = JSON.stringify({ "userId" : userId });
$.ajax({
url : url,
type : "POST",
traditional : true,
contentType : "application/json",
dataType : "json",
data : dat,
success : function (response) {
alert('success ' + response);
},
error : function (response) {
alert('error ' + response);
},
});
return false;
});
});
</script>
<script type="text/javascript">
$(function() {
$('#emailForm').submit(function() {
var form = $( this ),
url = form.attr('action'),
from = form.find('input[name="from"]').val(),
to = form.find('input[name="to"]').val(),
body = form.find('input[name="body"]').val(),
subject = form.find('input[name="subject"]').val(),
fileName = form.find('input[name="fileName"]').val(),
location = form.find('input[name="location"]').val(),
dat = JSON.stringify({ "from" : from,"to" : to,"body" : body,"subject" : subject,"fileName" : fileName,"location" : location });
$.ajax({
url : url,
type : "GET",
traditional : true,
contentType : "application/json",
dataType : "json",
data : dat,
success : function (response) {
alert('success ' + response);
},
error : function (response) {
alert('error ' + response);
},
});
return false;
});
});
</script>
</head>
<body>
<h2>Application</h2>
<form id="myForm" action="/application/history/save" method="POST">
<input type="text" name="userId" value="JUnit">
<input type="submit" value="Submit">
</form>
<form id="emailForm" action="/application/emailService/sendEmail" method="GET">
<input type="text" name="from" value="name#localhost.com">
<input type="text" name="to" value="user#localhost.com">
<input type="text" name="body" value="JUnit E-mail">
<input type="text" name="subject" value="Email">
<input type="text" name="fileName" value="attachment">
<input type="text" name="location" value="location">
<input type="submit" value="Send Email">
</form>
</body>
</html>
The 1st form works correctly and is deserilized in Spring MVC. A sample of that code is:
#Controller
#RequestMapping("/history/*")
public class HistoryController {
#RequestMapping(value = "save", method = RequestMethod.POST, headers = {"content-type=application/json"})
public #ResponseBody UserResponse save(#RequestBody User user) throws Exception {
UserResponse userResponse = new UserResponse();
return userResponse;
}
For the 2nd form I am getting exceptions:
#Controller
#RequestMapping("/emailService/*")
public class EmailController {
#RequestMapping(value = "sendEmail", method = RequestMethod.GET, headers = {"content-type=application/json"})
public void sendEmail(#RequestBody Email email) {
System.out.println("Email Body:" + " " + email.getBody());
System.out.println("Email To: " + " " + email.getTo());
}
}
Below is the stack trace:
java.io.EOFException: No content to map to Object due to end of input
org.codehaus.jackson.map.ObjectMapper._initForReading(ObjectMapper.java:2022)
org.codehaus.jackson.map.ObjectMapper._readMapAndClose(ObjectMapper.java:1974)
org.codehaus.jackson.map.ObjectMapper.readValue(ObjectMapper.java:1331)
org.springframework.http.converter.json.MappingJacksonHttpMessageConverter.readInternal(MappingJacksonHttpMessageConverter.java:135)
org.springframework.http.converter.AbstractHttpMessageConverter.read(AbstractHttpMessageConverter.java:154)
org.springframework.web.bind.annotation.support.HandlerMethodInvoker.readWithMessageConverters(HandlerMethodInvoker.java:633)
org.springframework.web.bind.annotation.support.HandlerMethodInvoker.resolveRequestBody(HandlerMethodInvoker.java:597)
org.springframework.web.bind.annotation.support.HandlerMethodInvoker.resolveHandlerArguments(HandlerMethodInvoker.java:346)
org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:171)
org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:426)
org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:414)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:790)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:549)
javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
I have tried using the POST too, but still the same problem. I need to use JSP to send JSON data to the Spring MVC Controller.
I am not sure where the problem is.
beans.xml
<context:component-scan base-package="com.web"/>
<mvc:annotation-driven/>
<context:annotation-config/>
Any ideas?
EDIT
public class Email implements Serializable {
private String from;
private String to;
private String body;
private String subject;
private String fileName;
private String location;
public Email() {
}
// Getters and setters
}
JSON sent is in form2 which is #emailForm.
You should check if you have set "content-length" header.
I ran into the same problem, but I used curl to verify the server side function.
The initial data section in my curl command is
-d "{'id':'123456', 'name':'QWERT'}"
After I changed the command to
-d '{"id":"123456", "name":"QWERT"}'
then it worked.
Hope this gives some hints.
I had this problem when I tried to use POST method with path parameter, but I forgot to put '#PathParam("id") Integer id', I just had 'Integer id ' in parameters.

Categories

Resources