How to upload resume in Angularjs by using Spring MyBatis
What
is Spring?
The
Spring Framework is an application framework and inversion of control
container for the Java platform. The framework's core features can be
used by any Java application, but there are extensions for building
web applications on top of the Java EE platform.
I
will create simple web app using SpringMVC +MyBatis
+ AngularJS to show data into the database(MYSQL).
Step1:
By
using Angular Js we can design below screen:

This is for the HTML code:
<html>
<body>
<div ng-app="myApp" class="container" ng-controller="regController" >
<form enctype="multipart/form-data">
<div>
<label>UploadResume<span
id="coll">*</span>:</label>
<input
type="file" id="file" name="file"
multiple ng-files="getTheFiles($files)" ng-model="file1"
accept=".doc, .docx,.ppt, .pptx,.pdf,.odt" />
<input
type="button" ng-click="uploadFiles()"
value="Upload" />
</div>
<script
type="text/javascript">
app.directive('ngFiles',
['$parse', function ($parse) {
function
fn_link(scope, element, attrs)
var
onChange = $parse(attrs.ngFiles);
element.on('change',
function (event) {
onChange(scope,
{ $files: event.target.files });
});
};
return
{
link:
fn_link
}
}])
app.controller('regController',
function($scope, $http) {
var
formdata = new FormData();
$scope.getTheFiles
= function ($files) {
console.log($files);
angular.forEach($files,
function (value, key) {
formdata.append('file',
value);
$scope.file1
=value.name;
});
};
//
NOW UPLOAD THE FILES.
$scope.uploadFiles
= function () {
alert($scope.file1);
var
request = {
method:
'POST',
url:
'CourseService/uploadFile',
data:
formdata,
headers:
{
'Content-Type':
undefined
}
};
//
SEND THE FILES.
$http(request)
.success(function
(d) {
alert(JSON.stringify(d));
alert($scope.file1);
$scope.filepathloc=$scope.file1;
})
.error(function
(d) {
console.log(d);
alert("In
here"+d.status);
});
}
$scope.uploadFiles
= function() {
data["file1"]
= $scope.file1;.
}
});
</script>
</body>
</html>
Whenever
we run the application first of all it hits the service and then it
pass the call to controller,Where
it will perform the required action and then calls
the mapping resource in order to store the details in the database.
2.Create
packages for Controller, Mappers and Service :
Create
packages each for the Spring Controller, Model and Service classes
under the src/main/java folder. Also create a package for the MyBatis
Mapper class under the same src/main/java folder.
A
sample snapshot of the project after the package creation is as shown
below:
3.Create
classes for Model:
Create
a POJO class named Student.java and Student.java inside the
package com.mybatis.model to include the details of the Student model
entity during login.
Student.java:
package
com.mybatis.model;
public
Student
{
//
no need of getters and setters
}
Instead
of this just create an interface for the model
4.StudentMapper.java:
package
com.mybatis.mapper;
import
java.util.List;
import
java.util.Map;
public
interface StudentMapper
{
List<HashMap>
studentresume(Map
guiMapMessage);
}
5.MyBatis
Mapper:
A
Mapper in MyBatis framework is similar to the Repository tier in a
Spring environment. Crude SQL queries takes its place here. Create an
interface class name StudentMapper.java inside the
package com.mybatis.mapper to support the database
operations.
Studentmapper.xml:
<?xml
version="1.0" encoding="UTF-8"?>
<!DOCTYPE
mapper PUBLIC '-//mybatis.org//DTD Mapper 3.0//EN'
'http://mybatis.org/dtd/mybatis-3-mapper.dtd'>
<mapper
namespace='com.mybatis.mappers.StudentMapper'>
<insert
id="studentresume"
parameterType="java.util.Map">
INSERT
INTO student (uploadresume) VALUES (#{file1});
</insert>
</mapper>
where
Uploadresume are the field name or column name in MYSQL DB and where
class condition should be mentioned in ng-model name in view page.
6.Create
classes for Service:
Create
an interface class named StudentService.java inside the package
com.mouri.service to support the service tier operations.
StudentService.java
:
package
com.mouri.service ;
import
java.util.List;
import
java.util.Map;
public
interface StudentService
{
void
studentresume(Map guiMapMessage);
}
Create
a service tier implementation class (a POJO indeed) named
StudentServiceImpl.java inside the package com.mouri.serviceImpl.
This is where the application logic goes –
either
to save the student resume into the database.
7.Create
a service implementation :
Create
a service tier implementation class (a POJO indeed) named
StudentServiceImpl.java
inside
the package com.mouri.serviceImpl. This is where the application
logic goes –
either
to select the student details into the database.
StudentServiceImpl.java:
package
com.mouri.serviceImpl;
import
java.util.List;
import
java.util.Map;
import
java.util.HashMap;
import
org.mybatis.spring.SqlSessionFactoryBean;
import
org.springframework.beans.factory.annotation.Autowired;
import
org.springframework.beans.factory.annotation.Qualifier;
import
org.springframework.stereotype.Service;
import
com.mybatis.mappers.StudentMapper;
import
com.mouri.service.StudentService;
@Service
public
class StudentServiceImpl implements StudentService
{
@Autowired
private
StudentMapper studentMapper;
@Autowired
@Qualifier("studentSessionFactory")
private
SqlSessionFactoryBean studentSessionFactory;
//insert data
@Override
public
List<HashMap> studentresume(Map guiMapMessage) {
//
TODO Auto-generated method stub
System.out.println("insert data...");
return
studentMapper.studentresume(guiMapMessage);
}
}
8.Create
class for Controller:
Create
a Controller tier POJO class named StudentController.java inside the
package
Controller:
RESTful
Web services controller is the way the HTTP response body is created.
REST
Web service controller simply returns the object and the object data
is written directly to the HTTP response as JSON/XML.
StudentController.java
:
@Controller
@RequestMapping(value
= { "/CourseService" })
public
class StudentController {
@Autowired
private
StudentService studentService;
public
static Map<String, Object> jsonToMap(String jsonStr) throws
JSONException {
Map<String,
Object> retMap = new HashMap<String, Object>();
JSONObject
jsonObject = new JSONObject(jsonStr);
if
( jsonObject != null)
{
retMap
= toMap(jsonObject);
}
return
retMap;
}
//General
method to convert JSON object to Map.
public
static Map<String, Object> toMap(JSONObject object) throws
JSONException {
Map<String,
Object> map = new HashMap<String, Object>();
Iterator<String>
keysItr = object.keys();
while
(keysItr.hasNext()) {
String
key = keysItr.next();
Object
value = object.get(key);
if
(value instanceof JSONArray)
{
value = toList((JSONArray) value);
}
else
if (value instanceof JSONObject)
{
value
= toMap((JSONObject) value);
}
map.put(key,
value);
}
return
map;
}
//General
method to convert JSONArray to Map.
public
static List<Object> toList(JSONArray array) throws
JSONException {
List<Object>
list = new ArrayList<Object>();
for
(int i = 0; i < array.length(); i++) {
Object
value = array.get(i);
if
(value instanceof JSONArray) {
value
= toList((JSONArray) value);
}
else if (value instanceof JSONObject) {
value
= toMap((JSONObject) value);
}
list.add(value);
}
return
list;
}
private
static final Logger logger =
LoggerFactory.getLogger(StudentController.class);
@RequestMapping(value
= "/uploadFile", headers = "content-type=multipart/*",
method = RequestMethod.POST, consumes = "application/json")
public
@ResponseBody Map uploadFileHandler(@RequestBody MultipartFile
file,HttpServletRequest request) {
Map
returnMapMessage = new HashMap();
System.out.println("In
uploadFileHandler");
File
dir;
byte[]
bytes;
if
(file != null) {
if
(!file.isEmpty()) {
System.out.println("In
If");
try
{
System.out.println("In
try");
bytes = file.getBytes();
String rootPath
=request.getSession().getServletContext().getRealPath("/resumes");
dir = new File(rootPath);
System.out.println("path"+dir.getAbsolutePath());
if
(!dir.exists())
dir.mkdirs();
// for creating a new directory
//
file.getOriginalFilename() exists in dir
//
if not exists
//
******
//
Create the file on server
File
serverFile = new File(dir.getAbsolutePath() + File.separator +
file.getOriginalFilename());
BufferedOutputStream
stream = new BufferedOutputStream(new FileOutputStream(serverFile));
stream.write(bytes);
logger.info("Server
File Location=" + serverFile.getAbsolutePath());
System.out.println("In
success" + serverFile.getAbsolutePath());
returnMapMessage.put("upload",
"success");
returnMapMessage.put("fileName",
dir.getAbsolutePath()
+ File.separator + file.getOriginalFilename());
rootPath
= "D:/Workspace for
eclipse/StudentJobApplication/webapp/resumes";
dir = new File(rootPath);
System.out.println("path"+dir.getAbsolutePath());
if
(!dir.exists())
dir.mkdirs();
serverFile
= new File(dir.getAbsolutePath() + File.separator +
file.getOriginalFilename());
stream
= new BufferedOutputStream(new FileOutputStream(serverFile));
stream.write(bytes);
stream.close();
System.out.println("In
success" + serverFile.getAbsolutePath());
/* Assert.assertTrue(dir.delete());*/
//
****
//
else upload failed and corresponding error text
}
catch(Exception
e) {
System.out.println("In
catch");
returnMapMessage.put("upload",
"failed");
returnMapMessage.put("errorText",
"catch
You failed to upload " + file.getOriginalFilename() + " =>
" + e.getMessage());
}
}
else
{
System.out.println("In
else");
returnMapMessage.put("upload",
"failed");
returnMapMessage.put("errorText",
"firdtYou
failed to upload " + file.getOriginalFilename() + " =>
as file is empty");
}
}
else {
returnMapMessage.put("upload",
"failed");
returnMapMessage.put("errorText",
"You failed to upload fiel => as no file is uploaded");
}
return
returnMapMessage;
}
Here,
If
you want dispatcher-servlet.xml, web.xml, Config.xml, Please
click to refer below link
9.The
Data in the Database:
A
Sample snapshot as shown below:
As you can observe
that all the details will be fetched into the student table
successfully.
Thanks &
Regards,
Leela Maruthi Borra,
Technical Trainee,
MOURI Tech PVT LTD.
http://www.mouritech.com/


Comments
Post a Comment