Hallo Leute, ich versuche selbst eine Full-Stack-Website zu erstellen. Ich bin Spring-Entwickler und versuche Angular zu lernen. Schauen wir uns mein Problem an. Mein Code funktioniert, aber er ist sehr langsam. Ich lade ein Foto des Programms hoch Es kann nicht angezeigt werden, manchmal dauerte es 40 bis 60 Sekunden. Ich denke, das ist nicht normal. Wenn ich auf die Schaltfläche „Hochladen“ geklickt habe, wird es in der Datenbank gespeichert, wird aber nicht auf der Front-End-Webseite angezeigt. Ich werde mein Back-End und die Vorderseite senden Ende Code: Bekommt jemand diesen Fehler schon einmal?
Upload Photo
onFileSelected(event: Event): void {
const input = event.target as HTMLInputElement;
if (input?.files?.length) {
const file = input.files[0];
// Yükleme başladığında isLoading'yi true yapıyoruz
this.isLoading = true;
// Fotoğraf yükleme servisini çağırıyoruz
this.productService.uploadPhoto(this.product.id, file).subscribe({
next: (response) => {
// Fotoğraf başarıyla yüklendiyse, URL'yi güncelliyoruz
this.product.imageUrl = response;
console.log("Fotoğraf başarıyla yüklendi: ", response);
},
error: (error) => {
// Hata durumunda kullanıcıya uygun bir mesaj gösteriyoruz
this.isLoading = false; // Hata oluştuğunda spinner'ı kapatıyoruz
if (error.status === 400) {
alert('Geçersiz dosya formatı veya dosya boyutu fazla. Lütfen tekrar deneyin.');
} else if (error.status === 500) {
alert('Sunucu hatası oluştu. Lütfen daha sonra tekrar deneyin.');
} else {
alert('Fotoğraf yüklenirken bir hata oluştu. Lütfen tekrar deneyin.');
}
console.error("Fotoğraf yüklenirken hata oluştu: ", error);
},
complete: () => {
// Yükleme işlemi tamamlandıktan sonra spinner'ı kapatıyoruz
this.isLoading = false;
}
});
}
}
uploadPhoto(productId:number,file:File) : Observable {
const formData = new FormData();
formData.append('file',file,file.name);
return this.http.post(`http://localhost:8080/v1/photos/upload/${productId}`, formData,{responseType: 'text' as 'json' });
}
Anwendungseigenschaften:
server.tomcat.connection-timeout=60s
spring.servlet.multipart.max-file-size=3MB
spring.servlet.multipart.max-request-size=3MB
file.upload-dir = src/main/resources/static/uploads
@RestController
@RequestMapping("/v1/photos")
public class FileStorageController {
private final FileStorageService fileStorageService;
private final ProductRepository productRepository;
public FileStorageController(FileStorageService fileStorageService, ProductRepository productRepository) {
this.fileStorageService = fileStorageService;
this.productRepository = productRepository;
}
@PostMapping("/upload/{id}")
public ResponseEntity uploadfile(@PathVariable int id, @RequestParam("file") MultipartFile multipartFile){
try {
Product product = productRepository.findById(id).orElseThrow(() -> new IdNotFoundException(id));
String photoUrl = fileStorageService.saveFile(multipartFile);
product.setImageUrl(photoUrl);
productRepository.save(product);
return ResponseEntity.ok(photoUrl);
}catch (Exception e){
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error: " + e.getMessage());
}
}
}
@Service
public class FileStorageService {
private final String uploadDir;
private final long MAX_FILE_SIZE = 3 * 1024 * 1024 ;
// Constructor with @Value to read upload directory from application.properties
public FileStorageService(@Value("${file.upload-dir}") String uploadDir) {
this.uploadDir = Paths.get(uploadDir).toAbsolutePath().toString();
}
public String saveFile(MultipartFile file) throws IOException {
if (file.isEmpty()) {
throw new RuntimeException("File is empty!");
}
if(file.getSize() > MAX_FILE_SIZE){
throw new RuntimeException("File size exceeds the maximum allowed size of 3 MB.");
}
// Generate a unique file name
String fileName = UUID.randomUUID().toString() + "_" + file.getOriginalFilename();
Path filePath = Paths.get(uploadDir, fileName);
// Create directories if they don't exist
Files.createDirectories(filePath.getParent());
Files.write(filePath, file.getBytes());
return "/uploads/" + fileName;
}
}
Ich erwarte, mein Problem zu lösen oder meine Webanwendung schneller zu machen
Spring Boot Angular18 Foto hochladen ⇐ Java
-
- Similar Topics
- Replies
- Views
- Last post