1前提准备:导包 cos-26Dec2008.jar 2 3 41.配置默认上传路径 5 6public void configConstant(Constants me) { 7 * 8 * 9 String path = JFinal.me().getServletContext().getRealPath("/"); 10 me.setUploadedFileSaveDirectory(path+"\\upload\\"); 11 //事实证明,不配置它也会默认创建一个名为upload文件夹将上传的文件放进去。 12 //因此,上传路径的文件夹是不需要自己先创建好的。 13 * 14 * 15 } 16 17 18 192.jsp页面(enctype="multipart/form-data" 是必须的)action 看自己的哪个,我这里是user路由下的upload方法中接收文件 20<form action="user/upload" method="post" enctype="multipart/form-data"> 21 <div class="form-group"> 22 <label class="sr-only" for="inputfile">上传文件</label> 23 <input type="file" id="inputfile" name="file">//其实就这句有用 24 </div> 25 </form> 26 27 28 3.Control 29 public void upload(){ 30 /* 31 * 自定义保存路径 32 *String realPath = JFinal.me().getServletContext().getRealPath("/"); 33 *String savePath = realPath+"\\upload1\\"; 34 *UploadFile fine1 = getFile("file",savePath); 35 **/ 36 // 不填写保存路径 37 UploadFile fine = getFile("file");//file是jsp页面input type='file'的name 38 render("/edit.jsp"); 39 } 404.最近做项目用这个出现的一些问题,也许是我对文件上传的理解不够深。 41 1)如果upload方法上加了验证器Validator。真实的效果是文件上传之后才调用Validator。 42 2)如果不是上传表单,form中就千万别加 enctype="multipart/form-data" 43 3 务必将 getFile()方法凡在method的第一行位置。 44 4)关于文件上传改名写了个方法 有点乱乱的 但是管用。。 45 46 //上传新文件并删除旧文件,如果不上传应该就没有删除旧文件的必要吧。 47 public static File renameFile(UploadFile uploadFile, String oldFilePath) { 48 if (uploadFile != null) { 49 File f = uploadFile.getFile(); 50 String houzhui = f.getName() 51 .substring(f.getName().lastIndexOf(".")); 52 Long l = System.currentTimeMillis(); 53 String path = uploadFile.getSaveDirectory(); 54 if (oldFilePath != null && !"".equals(oldFilePath)) { 55 oldFilePath = oldFilePath 56 .substring(oldFilePath.indexOf("/") + 1); 57 File old = new File(path + oldFilePath); 58 boolean b = old.exists() ? old.delete() : false; 59 System.out.println(b); 60 } 61 File fn = new File(path + "pic" + l + houzhui);//名字这里设置规则就好了 62 f.renameTo(fn); 63 return fn; 64 } 65有待补充、
Jfinal 上传文件
Stella981
2021-10-11
1210 0 0
点赞
收藏
评论区
加载中...