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();
}
}
}
}
http-equiv="Content-Type" content="text/html; charset=UTF-8">
显示图片request, response);%>