相对路径的问题,可以解释的比较清楚的
我在java中保存的一张图片,想把图片保存到webroot目录下面的images文件夹中,
我保存方法的类的目录是src/com/ac990/dao/impl
怎么才能把文件保存到webroot目录下啊?
在线等···
[解决办法]
/* * 上传文件 */ public String uploadFile(File upload, String uploadFileName, String directory) { String path = "upload"; String filePath = ""; try { HttpServletRequest request = ServletActionContext.getRequest(); String fileName = uploadFileName; // 获取物理路径 String sPath = request.getRealPath(path+File.separator + directory)+File.separator; // 获取网络地址 filePath = path + "/" + directory + "/" + fileName; String outputFileName = sPath + fileName; File outputPathFile = new File(sPath); if (!outputPathFile.exists()) { outputPathFile.mkdirs(); } // 保存文件 File outputFile = new File(outputFileName); java.io.InputStream is = new FileInputStream(upload); java.io.OutputStream os = new java.io.FileOutputStream(outputFile); if (outputFile.exists()) outputFile.delete(); byte buffer[] = new byte[8192]; int count = 0; while ((count = is.read(buffer)) > 0) { os.write(buffer, 0, count); } os.close(); is.close(); } catch (Exception e) { e.printStackTrace(); } return filePath; }
[解决办法]
String filePath = "images/"+fileName;