struts2 File标签上传文件
1、action.class
private File pictureType; private String pictureTypeContentType; private String pictureTypeFileName; public String editType() throws IOException{ Type t=typeService.find(Type.class, id); System.out.println("id="+id); System.out.println(UploadPath); System.out.println(pictureTypeFileName); File saved=new File(UploadPath+Constants.TypeDir, t.getId()+"."+pictureTypeContentType.split("/")[1]); InputStream ins=null; OutputStream ous=null; try { saved.getParentFile().mkdirs(); ins=new FileInputStream(pictureType); ous=new FileOutputStream(saved); byte[] b=new byte[1024]; int len=0; while((len=ins.read(b))!=-1){ ous.write(b, 0, len); } } catch (Exception e) { e.printStackTrace(); }finally{ if(ous!=null){ ous.close(); } if(ins!=null){ ins.close(); } t.setPicUrl(Constants.TypeDir+"/"+t.getId()+"." + pictureTypeContentType.split("/")[1]); typeService.save(t); } return SUCCESS; }
2、表单
<s:form action="editType_manage" enctype="multipart/form-data"> <s:file label="修改商店图片" name="pictureType"></s:file> <s:submit value="确认修改" /> </s:form>
3、action得不到文件的几个原因
(1)三个变量,没有get-set方法
(2)Form没有设置enctype="multipart/form-data"