您的位置:首页 > Web前端 > JavaScript

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

2013-09-10 16:02 197 查看
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>

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: