如何获取Prestataires类型的对象,其中包含一些文本和文件(图像)类型的输入,仅包含基于Spring-Boot从后端存储在文件夹中的URL,并基于Angular 5在前端显示它?
我尝试了这段代码,但前端出现500错误,后端出现RuntimeException。
以下是实体议员:
import java.io.Serializable;
import java.util.Collection;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
@Entity
public class Prestataires implements Serializable
{
@Id @GeneratedValue
private Long id;
private String nom;
private String email;
private String tele;
private String fax;
private String rib;
private String adresse;
private String taches;
//This is the URL of the Photo
private String photo;
//-------------------Constructors--------------------
//--------------------Getters and Setters-------------
@ManyToOne
@JoinColumn(name="ID_PRESTATAIRES_TYPES")
private PrestatairesTypes prestatairesTypes;
}
这是处理文件上载和加载的类:
package smart.syndic.metier;
import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.stereotype.Service;
import org.springframework.util.FileSystemUtils;
import org.springframework.web.multipart.MultipartFile;
import smart.syndic.entities.Prestataires;
@Service
public class StorageService
{
private String imageCDN = "http://www.yourHost.com/fichiers/";
private Path rootLocation;
public String store(MultipartFile file, String chemin, Object p) {
String storedLocation = null;
rootLocation = Paths.get("fichiers/"+chemin+"/");
String filename = null;
filename =((Prestataires) p).getId()+"."+file.getOriginalFilename()
.substring(
file.getOriginalFilename().lastIndexOf(".") + 1);
try {
if(file.isEmpty()){
throw new StorageException("Failed to store Empty"
+ " File "+filename);
}
if(filename.contains(".."))
{
throw new StorageException("Cannot store file with relative path
"
+ "outside current directory "+filename);
}
Files.copy(file.getInputStream(),
this.rootLocation.resolve(filename),
StandardCopyOption.REPLACE_EXISTING);
storedLocation = imageCDN + filename;
} catch (IOException e) {
throw new StorageException("Failed to store file " + filename, e);
}
((Prestataires) p).setPhoto("fichiers/"+chemin+"/"+filename);
return storedLocation + chemin+"/";
}
// the method that load the file (picture)
public Resource loadFile(String filename) {
try {
Path file = rootLocation.resolve(filename);
Resource resource = new UrlResource(file.toUri());
if (resource.exists() || resource.isReadable()) {
return resource;
} else {
// The error that is shown in the backend
throw new RuntimeException("File doesn't exist or is not
readable!");
}
} catch (MalformedURLException e) {
throw new RuntimeException("FAIL!");
}
}
public void deleteAll() {
FileSystemUtils.deleteRecursively(rootLocation.toFile());
}
}
这是RestController:
package smart.syndic.web;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.method.
annotation.MvcUriComponentsBuilder;
import smart.syndic.dao.PrestatairesRepository;
import smart.syndic.dao.PrestatairesTypesRepository;
import smart.syndic.entities.Prestataires;
import smart.syndic.metier.StorageService;
@RestController
@CrossOrigin("*")
public class PrestatairesRestController
{
@Autowired
private PrestatairesRepository repository;
@Autowired
private PrestatairesTypesRepository repository2;
@Autowired
private StorageService storageService;
private List<String> files = new ArrayList<String>();
// Method for getting the Prestataires Object and loading the photo
@RequestMapping(value="/prestataires/{id}",
method=RequestMethod.GET)
public Prestataires getVilles(@PathVariable Long id)
{
return repository.findOne(id);
}
@RequestMapping(value="/prestataires",
method=RequestMethod.POST)
public Prestataires addVilles(Prestataires p,
@RequestParam("multipartFile") MultipartFile file)
{
Prestataires pp = null;
try{
pp = repository.save(p);
storageService.store(file, "prestataires",pp);
files.add(file.getOriginalFilename());
}catch(Exception e){
e.printStackTrace();
}
p.setPrestatairesTypes(
repository2.findOne(p.getPrestatairesTypes().getId()));
updateVilles(p.getId(), p);
return pp;
}
@RequestMapping(value="/prestataires/{id}",
method=RequestMethod.PUT)
public Prestataires updateVilles(
@PathVariable Long id,
@RequestBody Prestataires v)
{
v.setId(id);
return repository.save(v);
}
@RequestMapping(value="/prestataires/{id}",
method=RequestMethod.DELETE)
public boolean deleteVilles(@PathVariable Long id){
repository.delete(id);
return true;
}
}
这是前视图:
<div class="right_col" role="main">
<div class="">
<div class="page-title">
<div class="title_left">
<h3>Prestataires</h3>
</div>
</div>
<div class="clearfix"></div>
<div class="row">
<div class="col-md-12 col-sm-12 col-xs-12">
<div class="x_panel">
<div class="x_title">
<h2>Voir les Prestataires </h2>
<ul class="nav navbar-right panel_toolbox">
<li><a class="collapse-link"><i class="fa fa-chevron-up"></i></a>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown"
role="button" aria-expanded="false"><i class="fa fa-wrench"></i></a>
<ul class="dropdown-menu" role="menu">
<li><a routerLink="/ajouterPrestataires">Ajouter
Prestataires</a>
</li>
</ul>
</li>
<li><a class="close-link"><i class="fa fa-close"></i></a>
</li>
</ul>
<div class="clearfix"></div>
</div>
<div class="x_content">
<div class="x_content">
<p class="text-muted font-13 m-b-30">
</p>
<div id="containerPrestataires">
</div>
<form class="form-horizontal form-label-left">
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12"
for="motCle">Mot Clé <span class="required">*</span>
</label>
<div class="col-md-3 col-sm-3 col-xs-12">
<input (keyup)="getAllPrestataires(motCle)"
[(ngModel)]="motCle" type="text" id="motCle" name="motCle"
required="required" class="form-control col-md-7 col-xs-12">
</div>
<div class="col-md-6 col-sm-6 col-xs-12">
<select [(ngModel)]="size" name="size" class="form-control"
(change)="getAllPrestataires(motCle)">
<option [value]="5">Afficher 5 Par Page</option>
<option [value]="10" selected="selected">Afficher 10 Par
Page</option>
<option [value]="20">Afficher 20 Par Page</option>
<option [value]="30">Afficher 30 Par Page</option>
<option [value]="40">Afficher 40 Par Page</option>
<option [value]="50">Afficher 50 Par Page</option>
<option [value]="100">Afficher 100 Par Page</option>
</select>
</div>
</div>
</form>
<div class="clearfix"></div>
<div class="clearfix"></div>
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>Numero</th>
<th>Raison Social/Nom</th>
<th>Email</th>
<th>Telephone</th>
<th>Type</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let a of allPrestataires; let i = index">
<td>{{i+1}}</td>
<td>{{a.nom}}</td>
<td>{{a.email}}</td>
<td>{{a.tele}}</td>
<td>{{a.prestatairesTypes?.designation}}</td>
<td>
<!-- Button trigger modal -->
<button type="button" class="btn btn-info" data-
toggle="modal" data-target="#myModal"
(click)="modifierPrestataires1(a.id)">
Modifier
</button>
<!-- Button trigger modal Suppression -->
<button type="button" data-toggle="modal" data-
target="#myModalSupprimer"
class="btn btn-danger"
(click)="supprimerPrestataires1(a.id)">
Supprimer
</button>
</td>
</tr>
</tbody>
</table>
<div class="container">
<ul class="nav nav-pills pull-right">
<li class="clickable" [ngClass]="{'active':page == iii}"
*ngFor="let p of pages; let iii = index">
<a (click)="goToPage(iii)">{{iii+1}}</a>
</li>
</ul>
</div>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog"
aria-labelledby="myModalLabel">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"
aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Modifier
Prestataires</h4>
</div>
<div class="modal-body">
<form class="form-horizontal form-label-left"
enctype="multipart/form-data">
<div id="containerModifierPrestataires">
</div>
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-
12">Nom/Raison Social<span class="required">*</span></label>
<div class="col-md-6 col-sm-6 col-xs-12">
<input [(ngModel)]="nom" name="nom" class="form-
control col-md-7 col-xs-12" type="text" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-
12">Email<span class="required">*</span></label>
<div class="col-md-6 col-sm-6 col-xs-12">
<input [(ngModel)]="email" name="email" class="form-
control col-md-7 col-xs-12" type="email" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-
12">Téléphone<span class="required">*</span></label>
<div class="col-md-6 col-sm-6 col-xs-12">
<input [(ngModel)]="tele" name="tele" class="form-
control col-md-7 col-xs-12" type="text" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-
12">Fax<span class="required">*</span></label>
<div class="col-md-6 col-sm-6 col-xs-12">
<input [(ngModel)]="fax" name="fax" class="form-
control col-md-7 col-xs-12" type="text" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-
12">RIB<span class="required">*</span></label>
<div class="col-md-6 col-sm-6 col-xs-12">
<input [(ngModel)]="rib" name="rib" class="form-
control col-md-7 col-xs-12" type="text" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-
12">Adresse<span class="required">*</span></label>
<div class="col-md-6 col-sm-6 col-xs-12">
<textarea [(ngModel)]="adresse" name="adresse"
class="form-control col-md-7 col-xs-12" type="text" required>
</textarea>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-
12">Tâches<span class="required">*</span></label>
<div class="col-md-6 col-sm-6 col-xs-12">
<textarea [(ngModel)]="taches" name="taches"
class="form-control col-md-7 col-xs-12" type="text" required>
</textarea>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-
12">Photo/Logo<span class="required">*</span></label>
<div class="col-md-6 col-sm-6 col-xs-12">
<input name="multipartFileModifier" class="form-
control col-md-7 col-xs-12"
type="file" required="required"
(change)="handleFileInput($event)">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-
12">Image Preview</label>
<div class="col-md-6 col-sm-6 col-xs-12">
<img class="imagePrestataires" [src]="photo">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-
12">Nouveau Type<span class="required">*</span></label>
<div class="col-md-6 col-sm-6 col-xs-12">
<div class="input-group">
<select class="form-control" name="selectTypes"
[(ngModel)]="selectTypes">
<option selected="selected" *ngFor="let s of
tousLesPrestatairesTypes" [value]="s.id" >
{{s.designation}}
</option>
</select>
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-sm-6 col-xs-12 col-md-offset-
3">
<button class="btn btn-warning"
type="reset">Vider</button>
<button type="button" class="btn btn-success"
(click)="modifierPrestataires2()">Modifier</button>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-
dismiss="modal" id="fermer">Fermer</button>
</div>
</div>
</div>
</div>
<!-- /modal -->
<!-- Modal -->
<div class="modal fade" id="myModalSupprimer" tabindex="-1"
role="dialog" aria-labelledby="myModalLabel2">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"
aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel2">Supprimer
Prestataires</h4>
</div>
<div class="modal-body">
<form class="form-horizontal form-label-left">
<div id="containerSupprimerPrestataires">
</div>
<div class="form-group">
<div class="col-md-6 col-sm-6 col-xs-12 col-md-offset-
3">
<h2>
<label class="label label-danger">
Voulez-vous le supprimer maintenant?
</label>
</h2>
<button type="button" class="btn btn-warning"
(click)="supprimerPrestataires2()">OUI</button>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-
dismiss="modal">NO</button>
</div>
</div>
</div>
</div>
<!-- /modal -->
<div class="ln_solid"></div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
这是前端控制器:
import { Component, OnInit } from '@angular/core';
import {PrestatairesService} from "../../services/prestataires.service";
@Component({
selector: 'app-prestataires',
templateUrl: './prestataires.component.html',
styleUrls: ['./prestataires.component.css']
})
export class PrestatairesComponent implements OnInit {
motCle:any = "";
page:any = 0;
size:any = 5;
pages:any;
allPrestataires:any;
supprimer:any = 0;
nom:any;
email:any;
tele:any;
fax:any;
rib:any;
adresse:any;
taches:any;
photo:any;
onePrestataires:any;
tousLesPrestatairesTypes:any;
selectTypes:any;
fileToUpload:any;
imageURL:any;
constructor(private service:PrestatairesService)
{
}
ngOnInit() {
this.getAllPrestataires();
}
getAllPrestataires()
{
this.service.getAllPrestataires(this.motCle, this.page, this.size)
.subscribe(data=>{
this.allPrestataires = data.content;
this.pages = new Array(data.totalPages);
if(data.totalPages <= this.page)
{
this.page = 0;
this.getAllPrestataires();
}
}, err=>{
}, ()=>{
});
}
modifierPrestataires1(id:any)
{
this.service.modifierPrestataires1(id)
.subscribe(data=>{
this.onePrestataires = data;
this.nom = this.onePrestataires.nom;
this.email = this.onePrestataires.email;
this.tele = this.onePrestataires.tele;
this.fax = this.onePrestataires.fax;
this.rib = this.onePrestataires.rib;
this.adresse = this.onePrestataires.adresse;
this.taches = this.onePrestataires.taches;
this.photo = "http://localhost:8080/"+this.onePrestataires.photo;
}, err=>{
}, ()=>{
this.getAllTypes();
});
}
modifierPrestataires2()
{
// Code here to update Prestataires
}
supprimerPrestataires1(id:any){
this.supprimer = id;
}
supprimerPrestataires2()
{
this.service.supprimerPrestataires(this.supprimer)
.subscribe(data=>{
this.getAllPrestataires();
}, err=>{
}, ()=>{
});
}
goToPage(id:any)
{
this.page = id;
this.getAllPrestataires();
}
getAllTypes()
{
this.service.getAllTypes()
.subscribe(data=>{
this.tousLesPrestatairesTypes = data;
}, err=>{
}, ()=>{
});
}
handleFileInput(file:any)
{
this.fileToUpload = <File>file.target.files[0];
let reader = new FileReader();
reader.onload = (event:any)=>{
this.photo = event.target.result;
}
reader.readAsDataURL(this.fileToUpload);
}
}
这是Service类:
import {Injectable} from "@angular/core";
import {HttpClient, HttpEvent, HttpHeaders, HttpParams, HttpRequest} from
"@angular/common/http";
@Injectable()
export class PrestatairesService
{
host:string = "http://localhost:8080/";
constructor(private http:HttpClient)
{
}
getAllPrestataires(motCle:any, page:any, size:any)
{
return this.http.get(this.host + "prestataires?
motCle="+motCle+"&page="+page+"&size="+size);
}
supprimerPrestataires(id:any)
{
return this.http.delete(this.host + "prestataires/" + id);
}
getAllTypes()
{
return this.http.get(this.host + "prestatairesTypes");
}
ajouterType(model:any)
{
return this.http.post(this.host + "prestatairesTypes", model);
}
getOneType(id:any)
{
return this.http.get(this.host + "prestatairesTypes/" + id);
}
ajouterPrestataires(model:any)
{
return this.http.post(this.host + "prestataires", model);
}
uploadFile(model:any)
{
let formData = new FormData();
formData.append('multipartFile', model.file);
formData.append('nom', model.nom);
formData.append('email', model.email);
formData.append('rib', model.rib);
formData.append('taches', model.taches);
formData.append('fax', model.fax);
formData.append('adresse', model.adresse);
formData.append('tele', model.tele);
formData.append('prestatairesTypes', model.prestatairesTypes);
let params = new HttpParams();
const options = {
params: params,
reportProgress: true,
};
const req = new HttpRequest('POST', this.host+"prestataires", formData,
options);
return this.http.request(req);
}
modifierPrestataires1(id:any){
return this.http.get(this.host + "prestataires/" + id);
}
}
GET 404:
GET http://localhost:8080/fichiers/prestataires/48.jpg 404