方式1.将图片存入硬盘指定路径 通过请求将图片内容写入输出流中显示在页面
public static void showPic(String pic,HttpServletResponse response) {
try{
InputStream inputStream = null;
ServletOutputStream outputStream=response.getOutputStream();
response.reset();
response.setContentType("image/jpeg");
String savePath = "";
// 系统文件路径
String globalPath = FileUploadContext.getGlobalPath();
if (globalPath == null) {
globalPath = "D://software//";
}
savePath = globalPath+pic;
try {
inputStream = new FileInputStream(savePath);
int bufferSize = 4096;
byte[] b = new byte[bufferSize];
int n = 0;
do {
n = inputStream.read(b);
if (n > 0) {
outputStream.write(b, 0, n);
}
} while (n > 0);
outputStream.flush();
} finally {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
}
}catch(IOException e){
logger.error(e.getMessage());
}
}
public static String uploadPic(HttpServletRequest req , String errorPic){
MultipartFile file = ((DefaultMultipartHttpServletRequest) req).getFile("pic");
String fileName = errorPic;
if(file!=null && file.getSize() > 0){
try{
if(file.getSize()>10000000){
throw new BaseException("上传失败:文件大小不能超过10M");
}
String picPath = FileUploadContext.getGlobalPath();
fileName = FileUploadContext.nextFileName();
int point = fileName.lastIndexOf(".");
fileName = fileName.substring(0,point);
String realFileName = file.getOriginalFilename();
int len = realFileName.length();
point = realFileName.lastIndexOf(".");
String prefix = realFileName.substring(point,len);
if(prefix.equals("")){
throw new IllegalArgumentException("文件无扩展名!");
}else if (prefix.equalsIgnoreCase(".jpg")
|| prefix.equalsIgnoreCase(".gif")
|| prefix.equalsIgnoreCase(".bmp")) {
// system.out.println("upload file type is " + prefix);
fileName = fileName + prefix ;
} else {
throw new IllegalArgumentException("文件类型错误!");
}
String fileFullName = picPath + fileName;
File destFile = new File(fileFullName);
file.transferTo(destFile);
}catch(Exception e){
logger.error(e.getMessage());
return fileName;
}
}
return fileName;
}
方式2:将图片存入数据库blob字段中(如表数据量较大不推荐使用)
public static byte[] savePic(ServletContext context, String fileName) {
byte[] buf = null;//10k缓存
try{
String picPath = context.getRealPath("WEB-INF");
int point = picPath.lastIndexOf(File.separator);
picPath = picPath.substring(0,point);
picPath = picPath + fileName;
FileInputStream imgis = new FileInputStream(picPath);
int n = 0;