处理jsp页面直接访问服务器硬盘图片

来源:互联网 发布:diagbox软件 编辑:程序博客网 时间:2024/04/28 11:52
package org.o2o.sys.utils;import java.io.DataInputStream;import java.io.DataOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.util.Properties;import java.util.UUID;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;/** * 上传文件帮助类 * @author liumin *  */public class UploadUtil {private static String name="path";//保存上传的文件,并返回文件名public static String saveUploadFile(File upload) {// >> 获取路径String basePath = getPath();// >> 如果文件夹不存在,就创建File dir = new File(basePath);if (!dir.exists()) {dir.mkdirs(); // 递归的创建不存在的文件夹}// >> 拼接路径String string = upload.toString();String path = basePath + UUID.randomUUID().toString() + string.substring(string.length()-4, string.length());// >> 移动文件upload.renameTo(new File(path)); // 如果目标文件夹不存在,或是目标文件已存在,就会不成功,返回false,但不报错。return getFileName(path);}//获取文件名称    public static String getFileName(String path){    String end=path.substring(path.lastIndexOf("."),path.length());    return path.substring(path.length()-(end.length()+36),path.length());    }//获取本地服务器保存的图片位置public static String getPath(){Properties file=new Properties();try {file.load(UploadUtil.class.getClassLoader().getResourceAsStream("uploadpath.properties"));} catch (IOException e) {e.printStackTrace();}return file.getProperty(name);}//读取本地服务器硬盘上的图片,并显示到页面    public static void show(String fileName,HttpServletRequest request,HttpServletResponse response){    File file=new File(getPath()+fileName);    if(file.exists()&&!"".equals(fileName)){    try {DataOutputStream dos=new DataOutputStream(response.getOutputStream());DataInputStream dis=new DataInputStream(new FileInputStream(file.getAbsolutePath()));byte[] data=new byte[2048];while((dis.read(data))!=-1){dos.write(data);dos.flush();}dis.close();dos.close();} catch (IOException e) {e.printStackTrace();}    }}}

<%@ page language="java" contentType="text/html; charset=UTF-8"import="java.util.*,java.io.*" pageEncoding="UTF-8"%><%@ page import="org.o2o.sys.utils.UploadUtil"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>显示图片</title><% out.clear(); out = pageContext.pushBody(); response.setContentType("image/jpeg");//设置显示文件或图片的格式如:application/pdf String imgName = request.getParameter("fileName"); UploadUtil.show(imgName, request, response);%></head><body></body></html>

原创粉丝点击