将上传的文件下载到服务器装载项目的目录中的指定的文件中

如项目在D:\\tomcat\\workapps\\中那么项目呢的WEB-INF就在D:\\tomcat\\workapps\\projectName\\中,如果想在WEB-INF同目录中建一个loadFile文件夹放下载下来的文件,代码如下:

 //根据服务器的文件保存地址和原文件名创建目录文件全路径  
            File dstFile = new File(ServletActionContext.getRequest().getRealPath("/loadFile/")+"//"+filename); 
         // 判断路径中文件名是否都存在,不存在则新建文件目录
            File parent = dstFile.getParentFile();
		if(parent!=null&&!parent.exists()) { 
			parent.mkdirs(); 
		} 
//file是struts2获取到的File文件
            copy(file, dstFile);

copy()方法为:

private static final int BUFFER_SIZE = 16 * 1024; 
private static void copy(File src, File dst) {  
        InputStream in = null;  
        OutputStream out = null;  
        try {  
            in = new BufferedInputStream(new FileInputStream(src), BUFFER_SIZE);  
            out = new BufferedOutputStream(new FileOutputStream(dst),  
                    BUFFER_SIZE);  
            byte[] buffer = new byte[BUFFER_SIZE];  
            int len = 0;  
            while ((len = in.read(buffer)) > 0) {  
                out.write(buffer, 0, len);  
            }  
        } catch (Exception e) {  
            e.printStackTrace();  
        } finally {  
            if (null != in) {  
                try {  
                    in.close();  
                } catch (IOException e) {  
                    e.printStackTrace();  
                }  
            }  
            if (null != out) {  
                try {  
                    out.close();  
                } catch (IOException e) {  
                    e.printStackTrace();  
                }  
            }  
        }  
    }  

  

例如上传的文件为1.jpg,那么该文件保存的路径就是D:\\tomcat\\workapps\\projectName\\loadFile\\1.jpg

你可能感兴趣的:(struts2保存文件路径问题)