Spring Boot Angular18 Загрузка фотоJAVA

Программисты JAVA общаются здесь
Anonymous
Spring Boot Angular18 Загрузка фото

Сообщение Anonymous »

Я пытаюсь сделать на сайте полного стека. Я весенний разработчик и пытаюсь выучить угловой. Мой код работает, но он очень медленный. Я загружаю фотографию в программу, но она не может появиться, иногда это занимает 40 - 60 секунд. Я думаю, что это не нормально, когда я нажал кнопку загрузки, она сохраняется в базе данных, но она не будет отображаться на веб -странице передней части. У кого-нибудь была эта проблема раньше?

Код: Выделить всё












Upload Photo





< /code>
 onFileSelected(event: Event): void {
const input = event.target as HTMLInputElement;
if (input?.files?.length) {
const file = input.files[0];

// When the loading starts, we set isLoading to true
this.isLoading = true;

// We call the photo upload service
this.productService.uploadPhoto(this.product.id, file).subscribe({
next: (response) => {
// If the photo is successfully uploaded, we update the URL
this.product.imageUrl = response;
console.log("Photo uploaded successfully: ", response);
},
error: (error) => {
// In case of an error, we show the correct error message to the user
this.isLoading = false; // We hide the spinner when an error occurs
if (error.status === 400) {
alert('The file format is invalid or the file is too large. Please try again.');
} else if (error.status === 500) {
alert('A server error occurred. Please try again later.');
} else {
alert('There was an error trying to load the photo.  Please try again.');
}
console.error("An error occurred while uploading the photo: ", error);
},
complete: () => {
// After the installation process is completed, we hide the spinner
this.isLoading = false;
}
});
}
}
< /code>
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' });

}
< /code>
Свойства приложения: < /p>
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
< /code>
@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());
}

}

}
< /code>
@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;
}
}
Я хотел бы решить эту проблему, чтобы сделать мое веб -приложение быстрее.


Подробнее здесь: https://stackoverflow.com/questions/792 ... ding-photo

Вернуться в «JAVA»