在本节中,我们将创建一个file upload web应用程序。该申请包括注册表。在这种集成中,我们使用spring处理后端部分,使用angular处理前端部分。
一旦我们将应用程序部署到服务器上,就会生成一个注册页面。 用户可以填写所需的信息并上传图片。 请记住,图像大小不得超过1 mb。
使用任何ide来开发spring和hibernate项目。可能是myeclipse/eclipse/netbeans。在这里,我们正在使用eclipse。 用于数据库的mysql。 使用任何ide来开发angular项目。它可能是visual studio代码/sublime。在这里,我们正在使用visual studio code。 服务器: apache tomcat/jboss/glassfish/weblogic/websphere。
在这里,我们使用以下技术:
spring5 hibernate5 angular6 mysql
让我们创建数据库 fileuploadexample 。无需创建表,因为hibernate会自动创建它。
让我们看看我们需要遵循的spring目录结构:
要开发文件上传应用程序,请执行以下步骤: -
将依赖项添加到pom.xml文件。
pom.xml
4.0.0 com.nhooo fileuploadexample war 0.0.1-snapshot fileuploadexample maven webapp http://maven.apache.org 5.0.6.release 5.2.16.final 5.1.45 0.9.5.2 1.8 1.8 org.springframework spring-webmvc ${springframework.version} org.springframework spring-tx ${springframework.version} org.springframework spring-orm ${springframework.version} com.fasterxml.jackson.core jackson-databind 2.9.5 org.hibernate hibernate-core ${hibernate.version} mysql mysql-connector-java ${mysql.connector.version} com.mchange c3p0 ${c3po.version} javax.servlet javax.servlet-api 3.1.0 javax.servlet.jsp javax.servlet.jsp-api 2.3.1 javax.servlet jstl 1.2 javax.xml.bind jaxb-api 2.3.0 junit junit 3.8.1 test commons-fileupload commons-fileupload 1.3 org.apache.commons commons-dbcp2 2.0 fileuploadexample
创建配置类
我们执行基于注释的配置,而不是xml。因此,我们创建两个类并在其中指定所需的配置。
demoappconfig.java
package com.nhooo.fileuploadexample.config; import java.beans.propertyvetoexception; import java.io.ioexception; import java.util.properties; import javax.sql.datasource; import org.hibernate.sessionfactory; import org.springframework.beans.factory.annotation.autowired; import org.springframework.context.annotation.bean; import org.springframework.context.annotation.componentscan; import org.springframework.context.annotation.configuration; import org.springframework.context.annotation.propertysource; import org.springframework.core.env.environment; import org.springframework.orm.hibernate5.hibernatetransactionmanager; import org.springframework.orm.hibernate5.localsessionfactorybean; import org.springframework.transaction.annotation.enabletransactionmanagement; import org.springframework.web.multipart.commons.commonsmultipartresolver; import org.springframework.web.servlet.config.annotation.enablewebmvc; import org.springframework.web.servlet.config.annotation.webmvcconfigurer; import com.mchange.v2.c3p0.combopooleddatasource; @configuration @enablewebmvc @enabletransactionmanagement @componentscan("com.nhooo.fileuploadexample") @propertysource(value = { "classpath:persistence-mysql.properties" }) @propertysource(value = { "classpath:persistence-mysql.properties" }) @propertysource(value = { "classpath:application.properties" }) public class demoappconfig implements webmvcconfigurer { @autowired private environment env; @bean public datasource mydatasource() { // create connection pool combopooleddatasource mydatasource = new combopooleddatasource(); // set the jdbc driver try { mydatasource.setdriverclass("com.mysql.jdbc.driver"); } catch (propertyvetoexception exc) { throw new runtimeexception(exc); } // set database connection props mydatasource.setjdbc); mydatasource.setuser(env.getproperty("jdbc.user")); mydatasource.setpassword(env.getproperty("jdbc.password")); // set connection pool props mydatasource.setinitialpoolsize(getintproperty("connection.pool.initialpoolsize")); mydatasource.setminpoolsize(getintproperty("connection.pool.minpoolsize")); mydatasource.setmaxpoolsize(getintproperty("connection.pool.maxpoolsize")); mydatasource.setmaxidletime(getintproperty("connection.pool.maxidletime")); return mydatasource; } private properties gethibernateproperties() { // set hibernate properties properties props = new properties(); props.setproperty("hibernate.dialect", env.getproperty("hibernate.dialect")); props.setproperty("hibernate.show_sql", env.getproperty("hibernate.show_sql")); props.setproperty("hibernate.format_sql", env.getproperty("hibernate.format_sql")); props.setproperty("hibernate.hbm2ddl.auto", env.getproperty("hibernate.hbm2ddl")); return props; } // need a helper method // read environment property and convert to int private int getintproperty(string propname) { string propval = env.getproperty(propname); // now convert to int int intpropval = integer.parseint(propval); return intpropval; } @bean public localsessionfactorybean sessionfactory(){ // create session factorys localsessionfactorybean sessionfactory = new localsessionfactorybean(); // set the properties sessionfactory.setdatasource(mydatasource()); sessionfactory.setpackagestoscan(env.getproperty("hibernate.packagestoscan")); sessionfactory.sethibernateproperties(gethibernateproperties()); return sessionfactory; } @bean @autowired public hibernatetransactionmanager transactionmanager(sessionfactory sessionfactory) { // setup transaction manager based on session factory hibernatetransactionmanager txmanager = new hibernatetransactionmanager(); txmanager.setsessionfactory(sessionfactory); return txmanager; } @bean(name="multipartresolver") public commonsmultipartresolver getresolver() throws ioexception{ commonsmultipartresolver resolver = new commonsmultipartresolver(); //set the maximum allowed size (in bytes) for each individual file. // resolver.setmaxuploadsize(5242880);//5mb resolver.setmaxuploadsize(524288);//0.5mb //you may also set other available properties. return resolver; } }
myspringmvcdispatcherservletinitializer.java
package com.nhooo.fileuploadexample.config; import org.springframework.web.servlet.support.abstractannotationconfigdispatcherservletinitializer; public class myspringmvcdispatcherservletinitializer extends abstractannotationconfigdispatcherservletinitializer { @override protected class[] getrootconfigclasses() { // todo auto-generated method stub return null; } @override protected class[] getservletconfigclasses() { return new class[] { demoappconfig.class }; } @override protected string[] getservletmappings() { return new string[] { "/" }; } }
创建实体类
在这里,我们将创建一个entity/pojo(普通的旧java对象)类。
userdetail.java
package com.nhooo.fileuploadexample.entity; import javax.persistence.column; import javax.persistence.entity; import javax.persistence.generatedvalue; import javax.persistence.generationtype; import javax.persistence.id; import javax.persistence.table; @entity @table(name="user_detail") public class userdetail { @id @generatedvalue(strategy=generationtype.auto) @column(name="user_id") private int userid; @column(name="email_id") public string emailid; @column(name="name") public string name; @column(name="profile_image") public string profileimage; public userdetail() { } public userdetail(int userid, string emailid, string name, string profileimage) { super(); this.userid = userid; this.emailid = emailid; this.name = name; this.profileimage = profileimage; } public int getuserid() { return userid; } public void setuserid(int userid) { this.userid = userid; } public string getemailid() { return emailid; } public void setemailid(string emailid) { this.emailid = emailid; } public string getname() { return name; } public void setname(string name) { this.name = name; } public string getprofileimage() { return profileimage; } public void setprofileimage(string profileimage) { this.profileimage = profileimage; } @override public string tostring() { return "userdetail [userid=" userid ", emailid=" emailid ", name=" name ", profileimage=" profileimage "]"; } }
创建dao接口
在这里,我们正在创建dao接口以执行与数据库相关的操作。
userdao.java
package com.nhooo.fileuploadexample.dao.interfaces; import com.nhooo.fileuploadexample.entity.userdetail; public interface userdao { public int saveuser(userdetail userdetail); public userdetail getuserdetail(int userid); public int updateprofileimage(string profileimage , int userid); }
创建dao接口实现类
userdaoimpl.java
package com.nhooo.fileuploadexample.dao.implementation; import org.hibernate.session; import org.hibernate.sessionfactory; import org.hibernate.query.query; import org.springframework.beans.factory.annotation.autowired; import org.springframework.stereotype.repository; import com.nhooo.fileuploadexample.dao.interfaces.userdao; import com.nhooo.fileuploadexample.entity.userdetail; @repository("userdao") public class userdaoimpl implements userdao { @autowired sessionfactory sessionfactory; public int saveuser(userdetail userdetail) { session session = null; try { session = sessionfactory.getcurrentsession(); int status = (integer) session.save(userdetail); return status; } catch(exception exception) { system.out.println("exception in saving data into the database" exception); return 0; } finally { session.flush(); } } public userdetail getuserdetail(int userid) { session session = null; try { session = sessionfactory.getcurrentsession(); userdetail userdetail = session.get(userdetail.class, userid); return userdetail; } catch(exception exception) { system.out.println("exception in saving data into the database " exception); return null; } finally { session.flush(); } } public int updateprofileimage(string profileimage, int userid) { session session= sessionfactory.getcurrentsession(); int result; try { queryquery = session.createquery("update userdetail set profileimage = :profileimage where userid=:userid "); query.setparameter("profileimage", profileimage); query.setparameter("userid", userid); result = query.executeupdate(); if(result > 0) { return result; } else return -5; } catch(exception exception) { system.out.println("error while updating profileimage from dao :: " exception.getmessage()); return -5; } finally { session.flush(); } } }
创建服务层接口
在这里,我们正在创建一个服务层接口,充当dao和实体类之间的桥梁。
userservice.java
package com.nhooo.fileuploadexample.service.interfaces; import javax.servlet.http.httpsession; import org.springframework.web.multipart.multipartfile; import com.nhooo.fileuploadexample.entity.userdetail; public interface userservice { public int saveuser(userdetail userdetail); public userdetail getuserdetail(int userid); public int store(multipartfile file, int userid , httpsession session); }
创建服务层实现类
userserviceimpl.java
package com.nhooo.fileuploadexample.service.implementation; import java.nio.file.files; import java.nio.file.path; import java.nio.file.paths; import javax.servlet.http.httpsession; import javax.transaction.transactional; import org.springframework.beans.factory.annotation.autowired; import org.springframework.stereotype.service; import org.springframework.web.multipart.multipartfile; import com.nhooo.fileuploadexample.dao.interfaces.userdao; import com.nhooo.fileuploadexample.entity.userdetail; import com.nhooo.fileuploadexample.service.interfaces.userservice; @service("userservice") public class userserviceimpl implements userservice { @autowired private userdao userdao; @transactional public int saveuser(userdetail userdetail) { return userdao.saveuser(userdetail); } @transactional public userdetail getuserdetail(int userid) { return userdao.getuserdetail(userid); } @transactional public int store(multipartfile file, int userid, httpsession session) { path rootlocation = paths.get(session.getservletcontext().getrealpath("/resources/images")); system.out.println("rootlocation == " rootlocation); userdetail userdetail = this.getuserdetail(userid); string nameextension[] = file.getcontenttype().split("/"); string profileimage = userid "." nameextension[1]; system.out.println("profileimage :: " profileimage); if(userdetail.getuserid() > 0 ) { if(userdetail.getprofileimage() == null || userdetail.getprofileimage() == " " || userdetail.getprofileimage() == "" ) { try { files.copy(file.getinputstream(),rootlocation.resolve(profileimage)); int result = userdao.updateprofileimage(profileimage, userid); if(result > 0) return result; else return -5; } catch(exception exception) { system.out.println("error while uploading image catch:: " exception.getmessage()); return -5; } } else { try { //files.delete(rootlocation.resolve(profileimage)); files.delete(rootlocation.resolve(userdetail.getprofileimage())); files.copy(file.getinputstream(),rootlocation.resolve(profileimage)); int result = userdao.updateprofileimage(profileimage, userid); if(result > 0) return result; else return -5; } catch(exception exception) { system.out.println("error while uploading image when image is already exists :: " exception.getmessage()); return -5; } } } else { return 0; } } }
创建控制器类
usercontroller.java
package com.nhooo.fileuploadexample.restcontroller; import javax.servlet.http.httpsession; import org.springframework.beans.factory.annotation.autowired; import org.springframework.web.bind.annotation.crossorigin; import org.springframework.web.bind.annotation.pathvariable; import org.springframework.web.bind.annotation.postmapping; import org.springframework.web.bind.annotation.requestbody; import org.springframework.web.bind.annotation.requestmapping; import org.springframework.web.bind.annotation.requestparam; import org.springframework.web.bind.annotation.restcontroller; import org.springframework.web.multipart.multipartfile; import com.nhooo.fileuploadexample.entity.userdetail; import com.nhooo.fileuploadexample.service.interfaces.userservice; @restcontroller @requestmapping("/api") @crossorigin(origins = "http://localhost:4200", allowedheaders = "*") public class usercontroller { @autowired private userservice userservice; @postmapping("/saveuser") public int saveuser(@requestbody userdetail userdetail) { return userservice.saveuser(userdetail); } @postmapping("/uploadimage/{userid}") public int handlefileupload(@pathvariable int userid , @requestparam("file") multipartfile file, httpsession session) { return userservice.store(file, userid, session); } }
创建属性文件
在这里,我们正在项目的 src/main/resources 内部创建属性文件。
application.properties
spring.http.multipart.max-file-size=1024kb spring.http.multipart.max-request-size=1024kb
persistence-mysql.properties
## jdbc connection properties# jdbc.driver=com.mysql.jdbc.driver jdbc.url=jdbc:mysql://localhost:3306/fileuploadexample?usessl=false jdbc.user=root jdbc.password= ## connection pool properties# connection.pool.initialpoolsize=5 connection.pool.minpoolsize=5 connection.pool.maxpoolsize=20 connection.pool.maxidletime=3000 ## hibernate properties# hibernate.dialect=org.hibernate.dialect.mysql5dialect hibernate.show_sql=true hibernate.format_sql=true hibernate.hbm2ddl=update hibernate.packagestoscan=com.nhooo.fileuploadexample.entity
让我们看一下我们需要遵循的angular目录结构:
创建一个angular项目
让我们使用以下命令创建angular项目:
ng新的fileuploadexample
这里, fileuploadexample 是项目的名称。
使用以下命令在项目中安装引导程序。
npm install bootstrap@3.3.7 --save
现在,在style.css文件中包含以下代码。
@import "~bootstrap/dist/css/bootstrap.css";
生成组件
在visual studio中打开项目,然后使用以下命令生成angular组件:
ng g c register
我们还通过使用以下命令: -
ng gs services/userdetail
编辑 app.module.ts 文件 导入reactiveformsmodule -在这里,我们将导入 reactiveformsmodule 用于反应形式,并在imports数组中指定它。 导入httpmodule -在这里,我们将为服务器请求导入 httpmodule ,并在imports数组中指定它。 注册服务类-在这里,我们在提供者的数组中提到了服务类。
import { browsermodule } from '@angular/platform-browser'; import { ngmodule } from '@angular/core'; // import reactiveformsmodule for reactive form import { reactiveformsmodule } from '@angular/forms'; import { appcomponent } from './app.component'; import { registercomponent } from './register/register.component'; import { httpmodule } from '@angular/http'; @ngmodule({ declarations: [ appcomponent, registercomponent ], imports: [ browsermodule, reactiveformsmodule, httpmodule ], providers: [], bootstrap: [appcomponent] }) export class appmodule { }
编辑 app.component.html 文件
创建 userdetail.ts 类
让我们使用以下命令创建一个类: -
ng g类class/userdetail
现在,在 userdetail 类中指定必填字段。
export class userdetail { emailid : string; name : string; profileimage : string; }
此类的目的是将指定的字段与spring实体类的字段进行映射。
编辑 user-detail.service.ts 文件
import { injectable } from '@angular/core'; import { userdetail } from '../classes/user-detail'; import { observable } from 'rxjs'; import { http, requestoptions , headers } from '@angular/http'; @injectable({ providedin: 'root' }) export class userdetailservice { // base url private baseurl = "http://localhost:8080/fileuploadexample/api/"; constructor(private http: http) { } savedata(userdetail : userdetail) : observable{ let url = this.baseurl "saveuser"; return this.http.post(url,userdetail); } uploadfile( file: file , id : number ) : observable { let url = this.baseurl "uploadimage/" id ; const formdata: formdata = new formdata(); formdata.append('file', file); return this.http.post(url , formdata); } }
编辑 register.component.ts 文件
import { component, oninit } from '@angular/core'; import { formgroup, formcontrol, validators } from '@angular/forms'; import { userdetail } from '../classes/user-detail'; import { userdetailservice } from '../services/user-detail.service'; import { jsonpfactory } from '@angular/http/src/http_module'; @component({ selector: 'app-register', templateurl: './register.component.html', styleurls: ['./register.component.css'] }) export class registercomponent implements oninit { selectedfiles: filelist; currentfileupload: file; private userdetail = new userdetail(); constructor(private userdetailservice : userdetailservice) { } ngoninit() { } selectfile(event) { const file = event.target.files.item(0); if (file.type.match('image.*')) { var size = event.target.files[0].size; if(size > 1000000) { alert("size must not exceeds 1 mb"); this.form.get('profileimage').setvalue(""); } else { this.selectedfiles = event.target.files; } } else { alert('invalid format!'); } } // create the form object. form = new formgroup({ fullname : new formcontrol('' , validators.required), email : new formcontrol('' , validators.required), profileimage : new formcontrol() }); adminform(admininformation) { this.userdetail.name = this.fullname.value; this.userdetail.emailid = this.email.value; console.log(this.userdetail); this.userdetailservice.savedata(this.userdetail).subscribe( response => { let result = response.json(); console.log(result); if(result > 0 ) { if(this.selectedfiles != null) { this.currentfileupload = this.selectedfiles.item(0); console.log(this.currentfileupload); this.userdetailservice.uploadfile(this.currentfileupload , result).subscribe( res => { let re = res.json(); if(re > 0) { alert("file upload successfully "); this.form.get('fullname').setvalue(""); this.form.get('email').setvalue(""); this.form.get('profileimage').setvalue(""); } else{ alert("error while uploading fie details"); } }, err => { alert("error while uploading fie details"); } ); } } }, error => { console.log("error while saving data in the db"); } ); } get fullname(){ return this.form.get('fullname'); } get email(){ return this.form.get('email'); } }
编辑 register.component.html 文件
registration form