English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
في هذا القسم، سنقوم بإنشاء تطبيق إنترنت تحميل ملفات. يتضمن هذا الطلب قائمة بالتسجيل. في هذه الاتصال، نستخدم Spring للمعالجة الجزء الخلفي، ونستخدم Angular للمعالجة الجزء الأمامي.
بمجرد أن نقوم بتركيب التطبيق على الخادم، سيتم إنشاء صفحة التسجيل. يمكن للمستخدمين ملء المعلومات المطلوبة وتحميل الصور. تذكر أن حجم الصورة لا يجب أن يتجاوز 1 MB.
استخدام أي IDE لتطوير مشاريع Spring وHibernate. قد يكون MyEclipse/Eclipse/Netbeans. هنا، نستخدم Eclipse. MySQL كنظام قاعدة البيانات. استخدام أي IDE لتطوير مشاريع Angular. قد يكون Visual Studio Code/Sublime. هنا، نستخدم Visual Studio Code. الخادم: Apache Tomcat/JBoss/Glassfish/Weblogic/Websphere.
في هذا السياق، نستخدم التكنولوجيات التالية:
Spring5 Hibernate5 Angular6 MYSQL
دعونا ننشئ قاعدة البيانات fileuploadexample لا تحتاج إلى إنشاء جدول، لأن Hibernate سيقوم بإنشائه تلقائيًا.
دعونا نرى بنية مجلدات Spring التي يجب علينا اتباعها:
لإنشاء تطبيق تحميل ملفات، قم بتنفيذ الخطوات التالية: -
إضافة依赖يات إلى ملف pom.xml.
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.w3codebox</groupId> <artifactId>FileUploadExample</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>FileUploadExample Maven Webapp</name> <url>http://maven.apache.org</url> <properties> <springframework.version>5.0.6.RELEASE</springframework.version> <hibernate.version>5.2.16.Final</hibernate.version> <mysql.connector.version>5.1.45</mysql.connector.version> <c3po.version>0.9.5.2</c3po.version> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> </properties> <dependencies> <!-- Spring --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${springframework.version}</version> </dependency> <!-- إضافة Jackson لتحويلات JSON --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.9.5</version> </dependency> <!-- Hibernate --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>${hibernate.version}</version> </dependency> <!-- MySQL --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.connector.version}</version> </dependency> <!-- C3PO --> <dependency> <groupId>com.mchange</groupId> <artifactId>c3p0</artifactId> <version>${c3po.version}</version> </dependency> <!-- Servlet + JSP + JSTL --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>javax.servlet.jsp-api</artifactId> <version>2.3.1</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!-- إلى التعويض عن عدم وجود jaxb في java 9 --> <dependency> <groupId>javax.xml.bind</groupId> <artifactId>jaxb-api</artifactId> <version>2.3.0</version> </dependency> <!-- JUnit dependency --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-dbcp2 --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-dbcp2</artifactId> <version>2.0</version> </dependency> </dependencies> <build> <finalName>FileUploadExample</finalName> </build> </project>
إنشاء فئة تكوين
نحن نفذنا تكوين تعليقي بدلاً من XML. لذلك، قمنا بإنشاء اثنين من الفئات وحددنا التكوين المطلوب فيها.
DemoAppConfig.java
package com.w3codebox.FileUploadExample.config; استيراد java.beans.PropertyVetoException; استيراد java.io.IOException; استيراد java.util.Properties; استيراد javax.sql.DataSource; import org.hibernate.SessionFactory; استيراد org.springframework.beans.factory.annotation.Autowired; استيراد org.springframework.context.annotation.Bean; استيراد 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.w3codebox.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() { // إنشاء حاسوب الاتصال ComboPooledDataSource myDataSource = new ComboPooledDataSource(); // ضبط محرك JDBC try { myDataSource.setDriverClass("com.mysql.jdbc.Driver"); } catch (PropertyVetoException exc) { throw new RuntimeException(exc); } // ضبط خصائص اتصال قاعدة البيانات myDataSource.setJdbcUrl(env.getProperty("jdbc.url")); myDataSource.setUser(env.getProperty("jdbc.user")); myDataSource.setPassword(env.getProperty("jdbc.password")); // ضبط خصائص حاسوب الاتصال 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() { // ضبط خصائص Hibernate خصائص 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.w3codebox.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 (مثلاً جافا عادي)。
UserDetail.java
package com.w3codebox.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.w3codebox.FileUploadExample.DAO.interfaces; import com.w3codebox.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.w3codebox.FileUploadExample.DAO.implementation; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.query.Query; استيراد org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import com.w3codebox.FileUploadExample.DAO.interfaces.UserDAO; import com.w3codebox.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) sessionFactory.save(userDetail); return status; } إceptions(exception) { System.out.println("Exception in saving data into the database" + exception); الناتج = 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; } إceptions(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<UserDetail> query = session.createQuery("update UserDetail set profileImage = :profileImage where userId=:userID "); query.setParameter("profileImage", profileImage); query.setParameter("userID", userID); result = query.executeUpdate(); إذا (result > 0) { الناتج = result; } else return -5; } إceptions(exception) { System.out.println("Error while updating profileImage from DAO :: " + exception.getMessage()); الناتج = -5; } finally { session.flush(); } } }
إنشاء واجهة طبقة الخدمة
في هذا السياق، نحن نخلق واجهة طبقة الخدمة، التي تتصرف كجسر بين DAO و实体.
UserService.java
package com.w3codebox.FileUploadExample.service.interfaces; استيراد javax.servlet.http.HttpSession; استيراد org.springframework.web.multipart.MultipartFile; import com.w3codebox.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.w3codebox.FileUploadExample.service.implementation; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; استيراد javax.servlet.http.HttpSession; import javax.transaction.Transactional; استيراد org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; استيراد org.springframework.web.multipart.MultipartFile; import com.w3codebox.FileUploadExample.DAO.interfaces.UserDAO; import com.w3codebox.FileUploadExample.entity.UserDetail; import com.w3codebox.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); إذا (result > 0) الناتج = result; else الناتج = -5; } إceptions(exception) { System.out.println("error while uploading image catch:: " + exception.getMessage()); الناتج = -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); إذا (result > 0) الناتج = result; else الناتج = -5; } إceptions(exception) { System.out.println("خطأ أثناء تحميل الصورة عند وجود الصورة بالفعل :: " + exception.getMessage()); الناتج = -5; } } } آخره { الناتج = 0; } } }
إنشاء كلاس التحكم
UserController.java
باقة com.w3codebox.FileUploadExample.restController; استيراد javax.servlet.http.HttpSession; استيراد org.springframework.beans.factory.annotation.Autowired; استيراد org.springframework.web.bind.annotation.CrossOrigin; استيراد org.springframework.web.bind.annotation.PathVariable; استيراد org.springframework.web.bind.annotation.PostMapping; استيراد org.springframework.web.bind.annotation.RequestBody; استيراد org.springframework.web.bind.annotation.RequestMapping; استيراد org.springframework.web.bind.annotation.RequestParam; استيراد org.springframework.web.bind.annotation.RestController; استيراد org.springframework.web.multipart.MultipartFile; import com.w3codebox.FileUploadExample.entity.UserDetail; import com.w3codebox.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.initialPoolSize=5 connection.pool.minPoolSize=5 connection.pool.maxPoolSize=20 connection.pool.maxIdleTime=3000 ## إعدادات Hibernate <!-- hibernate.dialect=org.hibernate.dialect.MySQLDialect --> hibernate.dialect=org.hibernate.dialect.MySQL5Dialect hibernate.show_sql=true hibernate.format_sql=true hibernate.hbm2ddl=update hibernate.packagesToScan=com.w3codebox.FileUploadExample.entity
دعونا نرى بنية الملفات التي يجب أن نتبعها في Angular:
إنشاء مشروع Angular
دعونا نستخدم الأمر التالي لإنشاء مشروع Angular:
ng new FileUploadExample
في هذا المكان، FileUploadExample هذا هو اسم المشروع.
استخدم الأمر التالي لتثبيت الجدول الزمني في المشروع.
npm install [email protected] --save
الآن، في ملف style.css، شمل الكود التالي.
@import \
إنشاء المكون
افتح المشروع في Visual Studio ثم استخدم الأمر التالي لإنشاء مكون Angular:
ng g c Register
نحن نستخدم الأمر التالي أيضًا: -
ng gs services/UserDetail
تحرير app.module.ts ملف استيراد ReactiveFormsModule -في هذا المكان، سنقوم بجلب ReactiveFormsModule للبث الشكل، وقم بتحديد هذا في قائمة imports. استيراد HttpModule -في هذا المكان، سنقوم بجلب الطلب إلى الخادم HttpModule ، وفي مصفوفة imports تحديدها. تسجيل فئة الخدمة-في هذا المكان، ذكرنا فئة الخدمة في مصفوفة المقدمين.
استيراد {BrowserModule} من '@angular/platform-browser'; استيراد {NgModule} من '@angular/core'; // استيراد ReactiveFormsModule للشكل التفاعلي استيراد {ReactiveFormsModule} من '@angular/forms'; استيراد {AppComponent} من './app.component'; استيراد {RegisterComponent} من './register/register.component'; استيراد {HttpModule} من '@angular/http'; @NgModule({ declarations: [ AppComponent, RegisterComponent ], imports: [ BrowserModule, ReactiveFormsModule, HttpModule ], providers: [], bootstrap: [AppComponent] }) تصدير فئة AppModule {}
تحرير app.component.html ملف
<app-register></app-register>
إنشاء UserDetail.ts الفئة
لنستخدم الأمر التالي لإنشاء فئة: -
ng g class/UserDetail
الآن، في UserDetail تحديد الحقول الإلزامية داخل الفئة.
تصدير فئة UserDetail { emailId : string; name : string; profileImage : string; }
هدفي هذا النوع هو ربط الحقل المحدد بحقول الكائنات الفعلية للفئة Spring.
تحرير user-detail.service.ts ملف
استيراد {Injectable} من '@angular/core'; import { UserDetail } from '../classes/user-detail'; استيراد {Observable} من '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<any> { let url = this.baseUrl + "saveUser"; return this.http.post(url,userDetail); } uploadFile( file: File , id : number ) : Observable<any> { 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 file details"); } }, err => { alert("error while uploading file 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 ملف
<h2>نموذج التسجيل</h2> <form [formGroup]="form" #AdminInformation (ngSubmit)="AdminForm(AdminInformation)"> <div class="row"> <div class=" col-md-offset-1 col-md-4"> <label for="fullName"> الاسم </label> <input formControlName="fullName" class="form-control" type="text"> </div> </div> <div class="row"> <div class=" col-md-offset-1 col-md-4"> <label for="email">البريد الإلكتروني</label> <input formControlName="email" class="form-control" type="text"> </div> </div> <div class="row"> <div class=" col-md-offset-1 col-md-4"> <label for="profileImage">رفع الصورة</label> <input formControlName="profileImage" class="form-control" type="file" (change)="selectFile($event)"> </div> </div> <div class="row" style="margin-top: 40px;"> <div class="col-md-offset-1 col-md-4"> <button class="btn btn-md btn-primary btn-style" >حفظ</button> </div> </div> </form>
بعد الانتهاء، قدم URL على الموقع http: //localhost: 4200/في المتصفح. سيظهر الصفحة التالية:
الآن، يمكننا ملء المعلومات المطلوبة واختيار الملفات التي نريد رفعها.