文件上传 获取文件路径的两种方式:

文件上传  获取文件路径的两种方式:



/**
* 获取文件上传目录
* @return
*/
private File getUploadFileLocation(HttpServletRequest request){
File upload = null;
try {
//获取项目的编译类目录   class 位置
// File path = new File(ResourceUtils.getURL("classpath:").getPath());
//获取项目文件位置  项目位置
File path = new File(request.getSession().getServletContext().getRealPath( "/")) ;
if(!path.exists()) path = new File( "") ;
System. out.println( "**************** path:"+path.getAbsolutePath() + "****************") ;
//如果上传目录为/static/images/upload/,则可以如下获取:
upload = new File(path.getAbsolutePath() , WEB_FILE_LOCATION ) ;
if(!upload.exists()) upload.mkdirs() ;
System. out.println( "****************** upload url:"+upload.getAbsolutePath() + "****************") ;
} catch (Exception e) {
e.printStackTrace() ;
}
return upload ;
}

getUploadFileLocation().getAbsolutePath()    获取实际路径



import org.springframework.util.ResourceUtils ;


//获取项目的编译类目录   class 位置
 File path = new File(ResourceUtils.getURL("classpath:").getPath());
//获取项目文件位置  项目位置
File path = new File(request.getSession().getServletContext().getRealPath( "/" )) ;




private final String  WEB_FILE_LOCATION = "/fileupload";

    /**
     *  获取文件上传目录
     * @return
     */
    private File getUploadFileLocation(HttpServletRequest request){
        File upload = null;
        try {
            //获取跟目录
//            File path = new File(ResourceUtils.getURL("classpath:").getPath());
            File path = new File(request.getSession().getServletContext().getRealPath("/"));
            if(!path.exists()) path = new File("");
            System.out.println("**************** path:"+path.getAbsolutePath() + "****************");
            //如果上传目录为/static/images/upload/,则可以如下获取:
            upload = new File(path.getAbsolutePath(),WEB_FILE_LOCATION );
            if(!upload.exists()) upload.mkdirs();
            System.out.println("****************** upload url:"+upload.getAbsolutePath() + "****************");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return upload;
    }



我的个人网站 : zegoto.cn 欢迎来信                          希望能帮到你

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值