路劲方法访问图片或文件的java代码

package com.hss.custonline.web.controller;

import java.awt.Container;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.RenderingHints;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.util.Properties;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

import com.sun.image.codec.jpeg.ImageFormatException;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

/**
* 参数:
* path 路径类型
* file 文件名
* thumbnail {true} 如果有则输出缩略图
* @author iinmming
*
*/
public class ShowFile implements Controller {

public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
throws Exception {

boolean imageType = false;
boolean isThumbnail = false;
String thumbnail = request.getParameter("thumbnail");
if (thumbnail != null && thumbnail.equals("true")) {
isThumbnail = true;
}

Properties props = PropertiesLoaderUtils.loadAllProperties("upload.properties");

String path = request.getParameter("path");

path = path == null ? "uploadpath" : path;
String sysPath = props.getProperty(path);
ServletOutputStream out = response.getOutputStream();
String file1 = request.getParameter("file").equals("")|| request.getParameter("file").equals("null") ? "nopic.jpg" : request.getParameter("file");

System.out.println("!!file1: " + file1);


String filename = sysPath + file1; // 要打开的文件物理真实路径


int dot = filename.indexOf(".");
String fileType = filename.substring(dot + 1); // 后缀
int realFileDot = filename.lastIndexOf("/");
String fileRealName = filename.substring(realFileDot + 1); // 真正的文件名


// ---------------------------------------------------------------
// 设置MIME
// ---------------------------------------------------------------
if (fileType.equalsIgnoreCase("xls")) {
response.setContentType("application/vnd.ms-excel");
} else if (fileType.equalsIgnoreCase("doc")) {
response.setContentType("application/msword");
}

else if (fileType.equalsIgnoreCase("ppt")) {
response.setContentType("application/vnd.ms-powerpoint");
}

else if (fileType.equalsIgnoreCase("pdf")) {
response.setContentType("application/pdf");
} else if (fileType.equalsIgnoreCase("gif")) {
response.setContentType("image/gif");
imageType = true;
} else if (fileType.equalsIgnoreCase("jpg") || fileType.equalsIgnoreCase("jpeg")) {
response.setContentType("image/jpeg");
imageType = true;
} else if (fileType.equalsIgnoreCase("png")) {
response.setContentType("image/png");
imageType = true;
} else if (fileType.equalsIgnoreCase("bmp")) {
response.setContentType("image/x-xbitmap");
imageType = true;
}

else if (fileType.equalsIgnoreCase("zip")) {
response.setContentType("application/zip");
}

// ---------------------------------------------------------------
// create an input stream from file
// ---------------------------------------------------------------

response.setHeader("Content-disposition", "attachment; filename=" + fileRealName); // 设置下载信息

// locate the real file path
String fileName = filename;

// ServletContext sc = getServletContext();
// filename = sc.getRealPath("image.gif");转化虚拟Web路径为服务器物理路径

// System.out.println("试图打开文件: " + filename);

BufferedInputStream bis = null;
BufferedOutputStream bos = null;
File file = null;
FileInputStream fileInputStream = null;
try {
// 如果是图片类型且要求输出缩微图的情况
if (imageType && isThumbnail) {

bos = generateThumbnail(out, fileName, bos);

}


file = new File(fileName);
fileInputStream = new FileInputStream(file);

bis = new BufferedInputStream(fileInputStream);

bos = new BufferedOutputStream(out);

byte[] buff = new byte[2048];
int bytesRead;

while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}

} catch (java.io.FileNotFoundException ne) {
throw ne;
} catch (final MalformedURLException e) {
System.out.println("MalformedURLException.");
throw e;
} catch (final IOException e) {
System.out.println("IOException.");
throw e;
} finally {
if (bis != null) {
bis.close();
}
if (bos != null) {
bos.close();
}
if (fileInputStream != null) {
fileInputStream.close();
}

}

return null;
}

private BufferedOutputStream generateThumbnail(OutputStream out, String fileName,
BufferedOutputStream bos) throws IOException, ImageFormatException,
NumberFormatException {
Image image = Toolkit.getDefaultToolkit().getImage(fileName);
MediaTracker mediaTracker = new MediaTracker(new Container());
mediaTracker.addImage(image, 0);
try {
mediaTracker.waitForID(0);
} catch (InterruptedException ex) {
}
// determine thumbnail size from WIDTH and HEIGHT
int thumbWidth = Integer.parseInt("200");
int thumbHeight = Integer.parseInt("160");
double thumbRatio = (double) thumbWidth / (double) thumbHeight;
int imageWidth = image.getWidth(null);
int imageHeight = image.getHeight(null);
double imageRatio = (double) imageWidth / (double) imageHeight;
if (thumbRatio < imageRatio) {
thumbHeight = (int) (thumbWidth / imageRatio);
} else {
thumbWidth = (int) (thumbHeight * imageRatio);
}
// draw original image to thumbnail image object and
// scale it to the new size on-the-fly
BufferedImage thumbImage = new BufferedImage(thumbWidth, thumbHeight,
BufferedImage.TYPE_INT_RGB);
Graphics2D graphics2D = thumbImage.createGraphics();
graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
graphics2D.drawImage(image, 0, 0, thumbWidth, thumbHeight, null);
// save thumbnail image to OUTFILE
bos = new BufferedOutputStream(out);
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(bos);
JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(thumbImage);
int quality = Integer.parseInt("80");
quality = Math.max(0, Math.min(quality, 100));
param.setQuality((float) quality / 100.0f, false);
encoder.setJPEGEncodeParam(param);
encoder.encode(thumbImage);
out.close();
return bos;
}
}

你可能感兴趣的:(java,Web,servlet,Excel,sun)