Код: Выделить всё
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' });
}
Код: Выделить всё
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;
}
}
Подробнее здесь: https://stackoverflow.com/questions/792 ... ding-photo
Мобильная версия