/**
* @Title: ImageController.java
* @Description: TODO
* @author zhangyd-c
* @date 2015年8月18日 下午1:04:15
* @version 1.0
*/
package com.gcj.controller;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
*
* @Description
* @author (作者) zhangyd-c
* @date (开发日期) 2015年8月18日 下午1:04:15
* @version (版本) V1.0
* @since (该版本支持的JDK版本) : 1.7
* @modify (修改)
*
* @Review (审核人)
*/
@Controller
@RequestMapping("/image")
public class ImageController {
/**
* 根据头像地址,读取头像文件
*
* @param request
* @param response
* @param path
* @author zhangyd-c
* @date 2015年5月28日 上午9:21:02
* @return void
* @throws
*/
@RequestMapping("/getUserAvatar")
public void getUserLogo(HttpServletRequest request, HttpServletResponse response, String path) {
File file = new File(path); // 括号里参数为文件图片路径
if (!file.exists()) { // 如果文件不存在,则使用默认的图片
path = request.getSession().getServletContext().getRealPath("/") + "assets/img/gallery/image2.jpg";// 可指定项目内的任意图片文件
file = new File(path); // 括号里参数为文件图片路径
}
readyImage(response, file);
}
/**
* 读取文件
*
* @Description
* @author zhangyd-c
* @date 2015年10月10日 下午2:01:49
* @param response
* @param file
*/
public void readyImage(HttpServletResponse response, File file) {
response.setContentType("image/jpeg"); // 设置返回内容格式
InputStream in = null;
OutputStream os = null;
try {
in = new FileInputStream(file);
os = response.getOutputStream(); // 创建输出流
byte[] b = new byte[1024];
while (in.read(b) != -1) {
os.write(b);
}
os.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
}
if (os != null) {
os.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
应用场景:
1.上传头像后根据头像地址读取头像文件用于前台显示
2.图片预览