版权声明:本文由李章勇老师创作,请支持原创,谢谢 https://blog.csdn.net/weixin_37654790/article/details/85263944
用户在向服务器提交资料时,有时会提交一个图片,为了改善用户体验,我们会在用户提交图片后随之在前端页面上显示用户提交的图片或缩略图。比如,我们在一些考试类的网站上提交报名信息时,就会经常遇到这种情况。下面是一个工具类,可以返回显示用户提交的图片。
import javax.servlet.ServletContext;
/**
* 工具类,生成基于网站根目录的绝对路径
*/
public class UtilGetRealPath {
private static ServletContext servletContextAll;
//初始化方法,对serlvetContext进行获取
public static void init(ServletContext servletContext){
servletContextAll=servletContext;
}
public static String getRealPath(String childPath){
return servletContextAll.getRealPath(childPath);
}
}
-----------------------------------------------------------
import java.io.File;
import java.io.IOException;
/**
* 工具类,生成用户提交上来的图片文件对象
*/
public class UtilGenPhotoFile {
/*
返回一个String 路径
*/
public static String genPhotoFilePath(String fileName,String uid){
//1.选取生成在哪个文件夹
File dir=new File(UtilGetRealPath.getRealPath("/photoImg/"+uid));
//2.如果该文件夹不存在,则创建
if (!dir.exists()) {
dir.mkdirs();
}
return "/photoImg/"+uid+"/"+fileName;
}
/*
返回一个File对象
*/
public static File genPhotoFile(String fileName,String uid) throws IOException {
//1.选取生成在哪个文件夹
File dir=new File(UtilGetRealPath.getRealPath("/photoImg/"+uid));
//2.如果该文件夹不存在,则创建
if (!dir.exists()) {
dir.mkdirs();
}
//3.选取生成在哪个具体文件
File photoFile=new File(dir,fileName);
//4.如果该文件不存在,则创建
if (!photoFile.exists()) {
photoFile.createNewFile();
}
return photoFile;
}
}