MissingServletRequestPartException: Required request part file is not present using Ajax - java

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;
}

Related

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>

not responding while sending json object from jsp to servlet

This is not functioning. What might be the error? I wanted to get name and password from clientside in the form of json to servlet.
index.jsp
<script src=”http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js”>
</script>
<script type="text/html">
function callFun(){
var n = document.getElementById('n1').value;
var p = document.getElementById('n2').value;
var myData = {"mydata" :{"name":n,"password":p}};
$.ajax({
type:'POST',
url:'/Page',
data:{jsonData:JSON.stringify(myData)},
dataType:'json',
success:function(data){
alert(json["resultText"]);
}
});
}
</script>
<form>
Name:<input type="text" name="nam" id="n1"><br>
Password:<input type="password" name="password" id="n2"><br>
<input type="button" onclick="callFun()" value="submit">
</form>
this is servlet class Page.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
JSONObject newObj = new JSONObject();
try(){
String json = request.getParameter("jsonData");
JSONObject jsonData = (JSONObject) JSONValue.parse(json);
String name = (String) jsonData.get("name");
System.out.println(name));
}catch(JSONException e){
e.printStackTrace();
}
}
Did you mean alert(data["resultText"]);
Also note you are using an old version of Jquery AJAX. Check the official Jquery AJAX guide for current version. In current version you can use .fail call to get the error message
var request = $.ajax({
url: "script.php",
method: "POST",
data: { id : menuId },
dataType: "html"
});
request.done(function( msg ) {
$( "#log" ).html( msg );
});
request.fail(function( jqXHR, textStatus ) {
alert( "Request failed: " + textStatus ); //Dipslay the error here
});

REST #FormParam values are null

I have the following in html
<form name="myform" method="POST">
<input type="text" id="products" name="products" />
</form>
function myForm() {
var url = 'rest/products/details/';
var formData = $("#myform").serializeArray();
$.ajax({
url: url,
type: 'POST',
contentType : "application/x-www-form-urlencoded",
dataType: 'json',
data: formData,
success: function (data) {
//callfunc(data);
}
});
}
In Java server side I have the following
#POST
#Path("/details")
public List<Product> findProducts(#FormParam("products") String products) {
.....
.....
log.info("prod "+products); --> getting null
For some reason products is null even though I am passing correct values from html. What could be the reason for this?
function myForm() {
var url = 'rest/products/details/';
var formData = "products=asasa" ;
$.ajax({
url: url,
type: 'POST',
contentType : "application/x-www-form-urlencoded",
dataType: 'json',
data: formData,
success: function (data) {
//callfunc(data);
}
});
}
try this and remove #consumes annotation. the problem is in the $("#myform").serializeArray() function from jquery.
Try Consumes annotation
#POST
#Path("/details")
#Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public List<Product> findProducts(#FormParam("products") String products) {
.....
.....
Issue is rather silly,I was using name instead of id and that resulted in getting null in server side for all form elements. I have changed to
<form id="myform" method="POST">
it works well
However
<form name="myform" method="POST"> doesn't work.

angularjs spring rest file upload form

I made angularjs spring rest file upload by the following code it works well and save file ,now I want to add some input text like description to html form with file upload and save them What is the code I should add to formData() in angular controller to make this?
angularjs controller
var myDropzone = new Dropzone("div#file",
{ url: "#"
});
myDropzone.on("addedfile", function(file) {
$scope.file=file;
});
$scope.uploadFile=function(){
var formData=new FormData();
formData.append("file",$scope.file);
console.log(formData)
$http.post('/pagingpoc/app/newDocument', formData, {
transformRequest: function(data, headersGetterFunction) {
return data;
},
headers: { 'Content-Type': undefined }
}).success(function(data, status) {
console.log("Success ... " + status);
}).error(function(data, status) {
console.log("Error ... " + status);
});
$('#saveAttachmentModal').modal('hide');
};
html form
<form ng-submit="uploadFile()" enctype="multipart/form-data">
<div class="form-group">
<label>Description</label>
<textarea rows="5" cols="5" ng-model="description"></textarea><br>
</div>
<div id="file" class="dropzone"></div>
<div class="modal-footer">
<button type="button" class="btn btn-default"
data-dismiss="modal" ng-click="clear()">
<span class="glyphicon glyphicon-ban-circle"></span> Cancel
</button>
<button type="submit" class="btn btn-primary">
<span class="glyphicon glyphicon-save"></span> Save
</button>
</div>
</form>
Rest Controller
public void UploadFile(MultipartHttpServletRequest request,
HttpServletResponse response) throws IOException {
Attachment attachment=new Attachment();
Iterator<String> itr=request.getFileNames();
MultipartFile file=request.getFile(itr.next());
String fileName=file.getOriginalFilename();
attachment.setName(fileName);
attachmentRepository.save(attachment);
File dir = new File("/home/ali/");
if (dir.isDirectory())
{
File serverFile = new File(dir,fileName);
BufferedOutputStream stream = new BufferedOutputStream(
new FileOutputStream(serverFile));
stream.write(file.getBytes());
stream.close();
}else {
System.out.println("Error Found");
}
}
controller:
var myDropzone = new Dropzone("div#file", { url: "#"});
myDropzone.on("addedfile", function(file) {
$scope.file=file;
});
$scope.text = '';
$scope.uploadFile = function(){
var formData=new FormData();
formData.append("file",$scope.file);
formData.append("text",$scope.text); //here
$http.post('/pagingpoc/app/newDocument', formData, {
transformRequest: function(data, headersGetterFunction) {
return data;
},
headers: { 'Content-Type': undefined }
}).success(function(data, status) {
console.log("Success ... " + status);
}).error(function(data, status) {
console.log("Error ... " + status);
});
$('#saveAttachmentModal').modal('hide');
};
hmlt:
Description
Cancel
Save

the request doesn't contain a multipart/form-data or multipart/mixed stream, content type header is false

I wanna send an image through ajax but I get the following exception:
org.apache.commons.fileupload.FileUploadBase$InvalidContentTypeException: the request doesn't contain a multipart/form-data or multipart/mixed stream, content type header is false
surprisingly when I send this form regularly(not through ajax) form works fine.I tried changing Content-Type to multipart/form-data but then I get this exception:
org.apache.commons.fileupload.FileUploadException: the request was rejected because no multipart boundary was found
here is the jquery code:
$(document).ready(function() {
$("#myform").submit(function(e) {
e.preventDefault();
var data = new FormData();
data.append('file', document.formName.file.files[0]); // <-- possibly this line doesn't work
$.ajax({
url: 'upload.do',
data: data,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(res) {
}
});
});
});
and the form:
<form name="formName" enctype="multipart/form-data" id="myform" action="upload.do" method="POST">
<input type="file" name="file" id="input-file" />
<br>
<input type="submit" value="Upload images" class="upload" />
</form>
Try this:
$(document).ready(function() {
$('.upload').click(function() {
var input = document.getElementById('input-file');
file = input.files[0];
var data = new FormData();
data.append('file', file);
$.ajax({
url: 'upload.do',
data: data,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(res) {
}
});
});
});

Categories

Resources