spring引导中上传映像的java验证

pnwntuvh  于 2021-07-09  发布在  Java
关注(0)|答案(0)|浏览(179)

有人能帮我吗?我有一个问题,上传一个文件,我想验证,如果该文件是图像,只接受所有的图像格式,如jpg,png等,我也想限制上传图像的大小。我不知道我的回答是否正确。
另外,我在设置contenttype时出错,因为在将图像上载到s3之后,我检查了s3 bucket而不是显示图像,它会提示下载图像。对不起,我是英语初学者。
文件存储.java

public void upload(String path, String fileName,
       Optional<Map<String, String>> optionalMetaData,InputStream inputStream) {

        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentType("image/*");
        optionalMetaData.ifPresent(map -> {
            if (!map.isEmpty()) {
                map.forEach(objectMetadata::addUserMetadata);
            }
        });
        try {
            amazonS3.putObject(path, fileName, inputStream, objectMetadata);
        } catch (AmazonServiceException e) {
            throw new IllegalStateException("Failed to upload the file", e);
        }
    }

userserviceimpl.java文件

public class UserServiceImpl implements UserService {

    private final FileStore fileStore;

    @Autowired
    private TodoRepository repository;

    @Override
    public Todo saveUser(Long userId, MultipartFile file) {

      **//check if the file is empty**
        if (file.isEmpty()) {
            throw new IllegalStateException("Cannot upload empty file");
        }

      **//Check if the file is an image**
        if (!Arrays.asList(IMAGE_PNG.getMimeType(),
                IMAGE_BMP.getMimeType(),
                IMAGE_GIF.getMimeType(),
                IMAGE_JPEG.getMimeType()).contains(file.getContentType())) {
            throw new IllegalStateException("FIle uploaded is not an image");
        }

        //get file metadata
        Map<String, String> metadata = new HashMap<>();
        metadata.put("Content-Type", file.getContentType());
        metadata.put("Content-Length", String.valueOf(file.getSize()));

        //Save Image in S3 and then save path url in the database
        String path = String.format("%s/%s", BucketName.TODO_IMAGE.getBucketName(), UUID.randomUUID());
        String fileName = String.format("%s", file.getOriginalFilename());
        try {
            fileStore.upload(path, fileName, Optional.of(metadata), file.getInputStream());
        } catch (IOException e) {
            throw new IllegalStateException("Failed to upload file", e);
        }

        User user= User.builder()
                .imagePath(path)
                .imageFileName(fileName)
                .build();
        repository.save(user);
        return repository.findByUserId(user.getId());
    }

用户控制器.java

@PostMapping(value = "/uploadUserPhoto/{userId}", consumes = {MediaType.MULTIPART_FORM_DATA_VALUE})
    public APIResponse uploadUserPhoto(@PathVariable Long userId, @RequestPart MultipartFile inputFile) throws IOException {

        User result = userService.uploadUserPhoto(userId, inputFile);

        Map<String, String> tempMap = new HashMap<String, String>();

        tempMap.put("userId", String.valueOf(result.getId()));

        return new APIResponse(HttpStatus.OK, "Upload Photo User : " + result.getId(), tempMap);

    }

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题