java實現上傳和讀取圖片(視頻)

 

0 背景

    實現從前端上傳圖片(或視頻),後端保存在指定目錄下;再從前端讀取文件,進行顯示。

1 上傳代碼實現

    1.1 html

<!-- nzAction:後端提供上傳的接口  nzName:上傳參數的命名(與後端接收一致)  nzChange:ts(js)裏綁定的事件 -->
<nz-upload nzAction="api/image/xxx" nzName="uploadFile (nzChange)="handleChange($event)">

    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<ImageUploadResponse> 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

<!-- 圖片 -->
<img src="/api/image/xxx/{{fileName||'undifined'}}" style="width: 260px;height: 140px;"/>
<!-- 視頻 -->
<video controls="controls" style="width: 705px; height: 388px;margin: 0 auto;" src="/api/image/xxx/{{fileName}}"></video>

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

  @GetMapping(value = "/image/xxx/{fileName}", produces = MediaType.IMAGE_PNG_VALUE)
    public ResponseEntity<Resource> 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);
    }

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章