angularjs spring rest file upload form - java

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

Related

How to redirect to html page after AJAX get request

Part of index.html file :
<button id="getAllGroups" type="button" class="btn btn-primary">Groups</button>
Then my js file :
GET: $(document).ready(
function () {
// GET REQUEST
$("#getAllGroups").click(function (event) {
event.preventDefault();
ajaxGet();
});
// DO GET
function ajaxGet() {
$.ajax({
type: "GET",
url: "checkGroups",
success: function (result) {
if (result.status == "success") {
var custList = "";
$.each(result.data,
function (i, group) {
var Html = "<tr>" +
"<td>" + group.groupId + "</td>" +
"<td>" + group.groupName + "</td>" +
"</tr>";
console.log("Group checking: ", group);
$('#tbody').append(Html);
});
console.log("Success: ", result);
window.location.href = "groupsPagik"
} else {
console.log("Fail: ", result);
}
},
});
}
})
And my RestController :
#RestController
public class GroupController {
#Autowired
GroupService groupService;
#GetMapping("/checkGroups")
public ResponseEntity<Object> getAllGroups() {
ServiceResponse<List<Group>> response = new ServiceResponse<>("success", groupService.getAll());
return new ResponseEntity<Object>(response, HttpStatus.OK);
}
}
Everything good and if I print obtained data to the same page - index.html :
<div class="row">
<div class="col-md-8">
<table border="2">
<thead>
<th>Group Id</th>
<th>Group name</th>
</thead>
<tbody id="tbody">
</tbody>
</table>
</div>
</div>
But I want to print this data ( groups ) to new html page.
So this is my question how to do it : print obtained data not to the same page, but to another.

Send image with difference data type from angular 7 to Rest API in spring boot 2.0.5

I searched a lot in "stack overflow" and in other sites, no answer resolve my problem.
Angular html file:
<form (ngSubmit)="submit">
<div>
<input type="file" [(ngModel)]="data.image" name="image" (change)="onFileSelected($event)">
</div>
<div class="form">
<mat-form-field>
<input matInput [(ngModel)]="data.clientName" name="clientName">
</mat-form-field>
</div>
//........ Other inputs fields here//
</form>
Angular ts file:
public confirmAdd(): void {
const payload: FormData = new FormData();
payload.append('clientName', this.data.clientName);
payload.append('dateOfBirth', this.data.dateOfBirth.toString());
payload.append('mobileNumber', this.data.mobileNumber);
payload.append('email', this.data.email);
//...............other fields here ..........//
payload.append('image', this.selectedFile); == > the image
}
Angular Service ts file:
private httpHeaders = new HttpHeaders({
'Content- Type': 'multipart/form-data'
});
this.http.post(this.urlEndTestImage, payload {
headers: this.httpHeaders
}).subscribe(res => {
console.log(res)
});
spring boot Rest API:
#CrossOrigin(origins = {
"http://localhost:4200"
})
#RestController
#RequestMapping("/apiHorsesClub")
public class ClienteRestController {
#PostMapping("/upload")
public String uploadMultipartFile(#RequestParam("model") String clientNew, #RequestParam(value = "image") MultipartFile image) {
try {
ObjectMapper mapper = new ObjectMapper();
clientEntity client = mapper.readValue(clientNew, clientEntity.class);
client.setImage(image.getBytes());
clientService.save(client);
return "successfully -> filename=" + image.getOriginalFilename();
} catch (Exception e) {
return "FAIL!file's size > 500KB";
}
}
}
I am try to add more #RequestParam() and I am try #RequestPart() with the same name of fields but not work.
This image of postman request post:
You have missed , in your Service.
private httpHeaders = new HttpHeaders({'Content- Type':'multipart/form-data'});
this.http.post(this.urlEndTestImage, payload, { headers:this.httpHeaders })
.subscribe(
res => { console.log(res) } );
I solved my problem, the problem as you say #Sudarshana i don't match "model" in angular side, and after a lot search i found two method to send file with difference data:
Send by (Data JSON, file)
Angular html:
<form [formGroup]="profileForm" (ngSubmit)="onSubmit()">
<input type="hidden" name="size" value="1000000">
<div>
<input type="file" (change)="onFileSelected($event)">
</div>
<div>
<input type="text" formControlName="clientName" placeholder="client Name">
<input type="text" formControlName="lastName" placeholder="Last Name">
<input type="text" formControlName="age" placeholder="Age">
<button type="submit" name="upload">POST</button>
</div>
</form>
Angular ts:
profileForm = new FormGroup({
clientName : new FormControl(''),
lastName : new FormControl(''),
age : new FormControl('')
});
selectedFile = null;
public data:clientClass = new clientClass();
onFileSelected(event) {
this.selectedFile = event.target.files[0];
console.log(this.selectedFile);
}
onSubmit() {
let object = this.profileForm.value;
const payload = new FormData();
payload.append("addClient",JSON.stringify(object));
payload.append("image", this.selectedFile, this.selectedFile.name);
this.http.post(`http://localhost:8080/yourAPI/uploadTestEntity`,payload, {
responseType: 'text'}).subscribe(
(object) => {
this.profileForm.reset();
});
}
App modules file:
import { FormsModule, ReactiveFormsModule } from '#angular/forms';
#NgModule({
imports:[ BrowserModule, FormsModule,ReactiveFormsModule ]
})
Rest API:
#PostMapping("/uploadTestEntity")
public String uploadTestEntity(
#RequestParam("addClient") String clientNameEntityNew,
#RequestParam(value = "image") MultipartFile image) {
try {
ObjectMapper mapper = new ObjectMapper();
testEntity testEntity = mapper.readValue(clientNameEntityNew,testEntity.class);
testEntity.setImage(image.getBytes());
TestEntityService.save(testEntity);
return "File uploaded successfully! -> filename = "+ image.getOriginalFilename();
} catch ( Exception e) {
return "FAIL! Maybe You had uploaded the file before or the file's size > 500KB";
}
}
2- send file and Data as params and receive as params in Rest API:
Angular html:
<form (ngSubmit)="onSubmit()">
<input type="hidden" name="size" value="1000000">
<div>
<input type="file" name="image" (change)="onFileSelected($event)">
</div>
<div>
<input id="textauthor" [(ngModel)]="clientName" name="clientName" placeholder="Name">
<input id="textauthor" [(ngModel)]="lastName" name="lastName" placeholder="last
Name">
<input id="textauthor" [(ngModel)]="age" name="age" placeholder="age">
<button type="submit" name="upload">POST</button>
</div>
</form>
Angular ts:
clientName:string;
lastName:string;
age:string;
resData: any;
selectedFile = null;
onFileSelected(event) {
this.selectedFile = event.target.files[0];
console.log(this.selectedFile);
onSubmit() {
const payload = new FormData();
payload.append('clientName', this.clientName);
payload.append('lastName', this.lastName);
payload.append('age', this.age);
payload.append('image', this.selectedFile, this.selectedFile.name);
this.http.post(`http://localhost:8080/apiHorsesClub/uploadTestEntity`,
payload).subscribe((data: any) => { this.resData = data;console.log(this.resData);
});
}
Rest API:
#PostMapping("/uploadTestEntity")
public String uploadTestEntity(
#RequestParam("clientName") String clientName ,
#RequestParam("lastName") String lastName
#RequestParam("age") String age
,#RequestParam(value = "image") MultipartFile image) {
try {
testEntity testEntity = new testEntity();
testEntity.setImage(image.getBytes());
testEntity.setClientName(clientName);
testEntity.setLastName(lastName);
testEntity.setAge(age);
return "File uploaded successfully! -> filename = "+ image.getOriginalFilename();
} catch ( Exception e) {
return "FAIL! Maybe You had uploaded the file before or the file's size > 500KB";
}
}

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

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>

Show Servlet Response in some <div>

What I'm trying to do
I'm building a small webapp with Netbeans, which can search for a ZIP-Code. The layout is made with bootstrap.css. Now I made following form in my (index.jsp):
<form id="form_submit_search"
class="navbar-form navbar-right"
role="form"
action="zipSearchHandler"
method="get">
<div class="form-group">
<input name="tv_zip"
type="text"
placeholder="ZIP Code..."
class="form-control">
</div>
<button id="submit_search"
type="submit"
class="btn btn-success">Search</button>
</form>
When the Button is klicked following method in the servlet is getting called:
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String zipCode = request.getParameter("tv_zip");
System.out.println(zipCode + " habe den zip bekommen");
response.setContentType("text/html;charset=UTF-8");
List<String> list = new ArrayList<String>();
list.add("item1");
list.add("item2");
list.add("item3");
list.add(zipCode);
String json = new Gson().toJson(list);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
}
This give's me back a simple json-array, which is opened in a new site, but I'd like to show that response in some <div> in my index.jsp. How can I do that?
You could use something like this
$.ajax(
{
type: "POST",
url: "/TestServlet",
data: { tv_zip: '90210' }, // zipcode
dataType: "json",
success: function(response) {
// replace the contents of div with id=some_div with the response.
// You will want to format / tweak this.
$('#some_div').html(response);
},
error: function(xhr, ajaxOptions, thrownError) { alert(xhr.responseText); }
}
);

Categories

Resources