java 上傳圖片至本地 並讀取圖片在網頁中顯示
阿新 • • 發佈:2018-12-07
java 上傳圖片至本地 並讀取圖片在網頁中顯示
程式碼+圖片如下所示
一、程式碼
@Controller
public class ImageController {
private static Logger logger = LoggerFactory.getLogger(ImageController.class);
@Autowired
private ImageService imageService;
@ResponseBody
@RequestMapping(value="uploadImage", method = RequestMethod.POST, produces = "application/json;charset=utf-8" )
public void uploadImage(@RequestParam("file") MultipartFile[] files){
for (int i = 0; i < files.length; i++) {
MultipartFile file = files[i];
if (!file.isEmpty()) {
imageService.imageService(file);
}
}
}
@ResponseBody
@RequestMapping(value = "/getImage", method = RequestMethod.GET, produces = "application/json;charset=utf-8")
public void getImage(String filename, HttpServletResponse response){
imageService.getImage(filename,response);
}
}
@Service
public class ImageService {
/*
getOriginalFilename:獲取上傳時的檔名
getName:獲取表單中檔案元件的名字
*/
//將檔案寫入到本地
public void imageService(MultipartFile file){
FileOutputStream out = null;
try {
byte[] bytes = file.getBytes();
String path = "C:\\Users\\Desktop\\pitcture\\"+file.getOriginalFilename();
File newFile = new File(path);
out = new FileOutputStream(newFile);
out.write(bytes);
out.flush();
System.out.println("成功儲存至本地");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//從本地讀取檔案並返回到網頁中
public void getImage(String filename, HttpServletResponse response){
FileInputStream in = null;
ServletOutputStream out = null;
try {
File file = new File("C:\\Users\\Desktop\\pitcture\\"+filename);
in = new FileInputStream(file);
out = response.getOutputStream();
byte[] bytes = new byte[1024 * 10];
int len = 0;
while ((len = in.read(bytes)) != -1) {
out.write(bytes,0,len);
}
out.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
in.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
二、圖片
使用postman進行介面測試