我们在做图片上传时 可能会遇到很多问题!比如就拿我自己遇到的几个问题来说
问题1.上传图片后网页不显示但是图片确实传上去了
原因分析:我们在访问项目的时候一般是会将将项目发布到tomact下,所以我们上传图片的目录应该是获取到tomact下的根目录,而不是项目目录里的图片文件夹。
而获取tomcat绝对根目录的方式一般常用的有两种:
String filepath = ServletActionContext.getServletContext().getRealPath(“/images”);
这种获取方式比较死板,一般会很少使用
String filepath=request.getSession().getServletContext().getRealPath(“/”)+”images/”;
这种就会相对显得比较万能一点,一般情况下都可以使用!
下面将图片上传的两种详细方式贴出来:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
FormFile photo=menuForm.getPhoto(); //如图片不为空,则处理图片信息 System.out.println("photo:"+photo); if(!photo.toString().equals("")){ String filename = photo.getFileName(); // 文件名 String newFilename=menuService.getNewFileName(filename);// 使用uuid值作为文件名,防止重复覆盖; // System.out.println("filename:::::::::::::::::"+filename); newFilename = menuService.getNewFileName(filename);// 使用uuid值作为文件名,防止重复覆盖 int filesize = photo.getFileSize(); // 文件大小,可做上传大小限制 String filetype = photo.getContentType(); // 文件类型,可做图片类型限制。最好不要通过后缀名判断,通过tomcat下web.xml查询 // 上传图片 InputStream is = null; OutputStream os = null; try { is = photo.getInputStream(); /* String filepath="C:\\www\\diancan\\WebRoot\\images";*/ /* String filepath = ServletActionContext.getServletContext().getRealPath("/images");*/ String filepath=request.getSession().getServletContext().getRealPath("/")+"images/"; os = new FileOutputStream(filepath + "\\" + newFilename); int len = 0; byte[] bytes = new byte[1024]; while ((len = is.read(bytes)) > 0) { // 读一点 写出到os一点 os.write(bytes, 0, len); } } catch (Exception e) { e.printStackTrace(); } finally { try { is.close(); os.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } // 随机生成uuid值作为图片名 menu.setPic(newFilename); } |
方法二:基于struct的图片上传
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
//需要引入的属性 private File doc; //封装上传文件的属性 private String docFileName; //封装上传文件的名称属性 private String docContentType; //封装上传文件的类型属性 public String doAddMeal() throws Exception { if(docFileName!=null){ //判断是否选择了上传图片 // 得到当前web工程下的upload目录的在本机的绝对路径,如果没有这个文件夹则会创建 String targetDirectory = ServletActionContext.getServletContext().getRealPath("/mealimages"); //重命名上传文件 String targetFileName = generateFileName(docFileName); //在指定目录创建文件 File target = new File(targetDirectory, targetFileName); //把要上传的文件copy过去 FileUtils.copyFile(doc, target); meal.setMealImage(targetFileName); meal.setMealSummarize(meal.getMealSummarize()); mealBiz.addMeal(meal); } return "toShowMeal"; } |