第一步:建立一個springboot項目java
第二步:編寫controller層web
package com.atzhongruan.springboot_pngupload.controller; import org.apache.tomcat.util.http.fileupload.IOUtils; import org.springframework.core.io.InputStreamResource; import org.springframework.core.io.Resource; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import java.io.*; /** * @Author jose * date 2019 */ @RestController public class UploadController { /** * 圖片上傳 * @param file * @throws IOException */ @RequestMapping("/upload") public void upload(@RequestParam("file")MultipartFile file)throws IOException { File saveFile = new File("D:\\11.png"); FileOutputStream outputStream = new FileOutputStream(saveFile); IOUtils.copy(file.getInputStream(),outputStream); outputStream.close(); } /** * 圖片預覽 * @return * @throws FileNotFoundException */ @RequestMapping(value = "/image/preview",produces = MediaType.IMAGE_PNG_VALUE) public ResponseEntity<Resource> preview()throws FileNotFoundException { FileInputStream inputStream = new FileInputStream(new File("D:\\23.png")); InputStreamResource inputStreamResource = new InputStreamResource(inputStream); HttpHeaders httpHeaders = new HttpHeaders(); return new ResponseEntity<>(inputStreamResource,httpHeaders, HttpStatus.OK); } }
第三步:post請求spring