Код: Выделить всё
const [selectedImage, setSelectedImage] = useState(null);
function handleSubmit(){
axios.defaults.withCredentials = true;
axios.post('http://localhost:8080/api/image/',
selectedImage)
.then(response => {
if(response.status === 200){
console.log(response.data)
// window.location.href = "/user-dash"
} else
console.log("nope")
return Promise.reject("it broke")
})
.catch(error => console.error(error));
}
Код: Выделить всё
Upload and Display Image
{selectedImage && (
[img]{URL.createObjectURL(selectedImage)}
handleSubmit()}>Save
setSelectedImage(null)}>Remove
)}
{
console.log(event.target.files[0]);
setSelectedImage(event.target.files[0]);
}}
/>
Код: Выделить всё
@PostMapping(value = "/", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity uploadImage(@RequestParam(value = "myImage") MultipartFile file){
String response = imageDataService.uploadImage(file);
return ResponseEntity.status(HttpStatus.OK)
.body(response);
}
Код: Выделить всё
@Service
@AllArgsConstructor
public class ImageDataService {
private ImageDataRepository imageDataRepository;
public String uploadImage(MultipartFile file) {
try {
imageDataRepository.save(ImageData.builder()
.name(file.getOriginalFilename())
.type(file.getContentType())
.imageData(ImageUtil.compressImage(file.getBytes())).build());
} catch (IOException e) {
throw new RuntimeException(e);
}
return "Image uploaded successfully: " +
file.getOriginalFilename();
}
@Transactional
public ImageData getInfoByImageByName(String name) {
Optional dbImage = imageDataRepository.findByName(name);
return ImageData.builder()
.name(dbImage.get().getName())
.type(dbImage.get().getType())
.imageData(ImageUtil.decompressImage(dbImage.get().getImageData())).build();
}
@Transactional
public byte[] getImage(String name) {
Optional dbImage = imageDataRepository.findByName(name);
byte[] image = ImageUtil.decompressImage(dbImage.get().getImageData());
return image;
}
}
Код: Выделить всё
public interface ImageDataRepository extends JpaRepository {
Optional findByName(String name);
}
Код: Выделить всё
@Entity
@Table(name = "imageData")
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class ImageData {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String type;
@Lob
@Column(name = "imagedata", length = 1000)
private byte[] imageData;
}
Код: Выделить всё
axios.post('http://localhost:8080/api/image/',
selectedImage,{
headers:{
"Content-Type": "multipart/form-data; boundary=----WebKitFormBoundaryyEmKNDsBKjB7QEqu"
}
})
.then(response => {
if(response.status === 200){
console.log(response.data)
// window.location.href = "/user-dash"
} else
console.log("nope")
return Promise.reject("it broke")
})
.catch(error => console.error(error));
Подробнее здесь: https://stackoverflow.com/questions/781 ... g-boot-bac