java实现上传和读取图片(视频)

 

0 背景

    实现从前端上传图片(或视频),后端保存在指定目录下;再从前端读取文件,进行显示。

1 上传代码实现

    1.1 html



    1.2 ts

// 上传附件
    handleChange(info: { file: UploadFile }): void {
        switch (info.file.status) {
            case 'uploading':
                break;
            case 'done':
                this.response = info.file.response;//response为后端返回的一个对象
                this.fileName = info.file.response.fileName;
                break;
            case 'error':
                this.messageService.error('上传失败');
                break;
        }
    }

    1.3 Controller

@RestController
@RequestMapping("/api")
public class ImageResource {

    @PostMapping(value = "/image/xxx")
    public ResponseEntity uploadAISampleFile(@RequestParam(name = "uploadFile") MultipartFile file) {
        //保存文件(一般写在service里)
        String fileName = String.valueOf("s-"+System.currentTimeMillis());
        String fullFileName = fileName + ".png";
        Path path = Paths.get(properties.getImagePath(),fullFileName);  //在配置文件中定义;文件实际的存储地址
        deleteExistFile(path);

        System.out.println("save image to path: "+path.toString());
        File parentFile = path.getParent().toFile();
        if (!parentFile.exists()) {
            parentFile.mkdirs();
            log.info("parent directory create success:" + parentFile.getPath());
        }
        try {
            file.transferTo(path.toFile());
            log.info("file upload success :" + path.toString());
        } catch (Exception e) {
            log.error(e.getMessage());
            log.error("save image error:" + e);
        }

        //上传并保存成功后返回给前端的对象
        ImageUploadResponse imageUploadResponse = new ImageUploadResponse();
        String url = "/api/image/xxx/" + fileName; //自定义,用于显示时调用
        imageUploadResponse.setUrl(url);
        imageUploadResponse.setFileName(fileName);
        imageUploadResponse.setUploaded(true);
        return new ResponseEntity<>(imageUploadResponse, HttpStatus.OK);
    }
}

    1.4 ImageUploadResponse

public class ImageUploadResponse {
    private boolean uploaded;

    private String url;

    private String fileName;

    public boolean isUploaded() {
        return uploaded;
    }

    public void setUploaded(boolean uploaded) {
        this.uploaded = uploaded;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getFileName() {
        return fileName;
    }

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }

    @Override
    public String toString() {
        return "ImageUploadResponse{" +
            "uploaded=" + uploaded +
            ", url='" + url + '\'' +
            ", fileName='" + fileName + '\'' +
            '}';
    }
}

2 显示代码实现

    2.1 html





    2.2 controller(1.3提到的ImageResource里添加)

  @GetMapping(value = "/image/xxx/{fileName}", produces = MediaType.IMAGE_PNG_VALUE)
    public ResponseEntity AIImage(@PathVariable String fileName) throws IOException  {
        //一般写在service里
        String fullFileName = fileName + ".png";
        Path path = Paths.get(properties.getImagePath(),fullFfileName);
        if (!path.toFile().exists()) {
            Resource resource = resourceLoader.getResource("classpath:image" + File.separator + type.defaultFile());
            return resource.getInputStream();
        }
        System.out.println("get: "+path.toString());
        File file = path.toFile();
        
        //返回给前端的文件,可直接在html页面显示
        InputStream inputStream = new FileInputStream(file);
        InputStreamResource resource = new InputStreamResource(inputStream);
        return new ResponseEntity<>(resource, HttpStatus.OK);
    }

 

 

 

你可能感兴趣的:(intellij,java,angular)