Spring Boot Angular18 Uploading Photo

Discussão em 'Angular' iniciado por Ali Turgut, Dezembro 9, 2024.

  1. Ali Turgut

    Ali Turgut Guest

    Hey Guys I'm trying to do Full-stack website by myself actually ı'm spring developer and ı try to learn angular let's have a look my problem my code is working but it is very slow ı upload photo the program but it can not appear,sometimes it went to 40 - 60 seconds i think it is not normal when ı clicked the upload button it is saved in database but it won't show up in front end web page i will send my back end and front end code does anyone get this error before ?

    <div class="row">
    <!-- Product Image -->
    <div class="col-md-6 product-image">
    <img *ngIf="product.imageUrl; else uploadPhoto" [src]="product.imageUrl" class="img-fluid rounded shadow-lg">
    <div *ngIf="isLoading" class="loading-overlay">
    <div class="spinner"></div>
    </div>

    <ng-template #uploadPhoto>
    <div class="upload-container">
    <label class="upload-photo-btn">
    <input type="file" (change)="onFileSelected($event)" id="photoUpload" hidden>
    <span>Upload Photo</span>
    </label>
    </div>
    </ng-template>

    </div>


    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<string> {
    const formData = new FormData();
    formData.append('file',file,file.name);

    return this.http.post<string>(`http://localhost:8080/v1/photos/upload/${productId}`, formData,{responseType: 'text' as 'json' });

    }


    Application Properties :

    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<String> 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;
    }
    }


    I'm expecting to solve my problem or make more faster my web application

    Continue reading...

Compartilhe esta Página