📅  最后修改于: 2020-12-06 03:40:20             🧑  作者: Mango
在本节中,我们将创建一个File Upload Web应用程序。该申请包括注册表。在这种集成中,我们使用Spring处理后端部分,使用Angular处理前端部分。
在这里,我们使用以下技术:
让我们创建一个数据库fileuploadexample 。由于Hibernate自动创建了表,因此无需创建表。
让我们看看我们需要遵循的Spring目录结构:
要开发文件上传应用程序,请执行以下步骤:-
pom.xml
4.0.0
com.javatpoint
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
DemoAppConfig.java
package com.javatpoint.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.javatpoint.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.setJdbcUrl(env.getProperty("jdbc.url"));
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.javatpoint.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[] { "/" };
}
}
UserDetail.java
package com.javatpoint.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 + "]";
}
}
UserDAO.java
package com.javatpoint.FileUploadExample.DAO.interfaces;
import com.javatpoint.FileUploadExample.entity.UserDetail;
public interface UserDAO {
public int saveUser(UserDetail userDetail);
public UserDetail getUserDetail(int userId);
public int updateProfileImage(String profileImage , int userID);
}
UserDAOImpl.java
package com.javatpoint.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.javatpoint.FileUploadExample.DAO.interfaces.UserDAO;
import com.javatpoint.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
{
Query query = 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和Entity类之间的桥梁。
UserService.java
package com.javatpoint.FileUploadExample.service.interfaces;
import javax.servlet.http.HttpSession;
import org.springframework.web.multipart.MultipartFile;
import com.javatpoint.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.javatpoint.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.javatpoint.FileUploadExample.DAO.interfaces.UserDAO;
import com.javatpoint.FileUploadExample.entity.UserDetail;
import com.javatpoint.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.javatpoint.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.javatpoint.FileUploadExample.entity.UserDetail;
import com.javatpoint.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);
}
}
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.javatpoint.FileUploadExample.entity
让我们看看我们需要遵循的Angular目录结构:
让我们使用以下命令创建一个Angular项目:
ng新的FileUploadExample
在这里, FileUploadExample是项目的名称。
使用以下命令在项目中安装引导程序。
npm install bootstrap@3.3.7 --save
现在,在style.css文件中包含以下代码。
@import "~bootstrap/dist/css/bootstrap.css";
我们还使用以下命令创建服务类:-
ng gs services / UserDetail
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 { }
让我们使用以下命令创建一个类:-
ng g class classes / UserDetail
现在,在UserDetail类中指定必填字段。
export class UserDetail {
emailId : string;
name : string;
profileImage : string;
}
该类的目的是将指定的字段与Spring实体类的字段进行映射。
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);
}
}
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');
}
}
Registration form
完成后,在Web浏览器中提供URL http:// localhost:4200 /。出现以下网页:
现在,我们可以填写所需的信息,然后选择需要上传的文件。