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

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>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值