Struts2对文件的上传已经做了很好的封装,我们的上传文件会被拦截!
// url 是file的路径这几个url必须一至! public class UploadAction extends ActionSupport { private File url; private String urlContentType; //上传文件类型 private String urlFileName; //上传文件的真实名字 private String destPath="/download"; //上传文件的地址目录 getter(); setter(); //保存上传资源 public String saveUpload() throws IOException{ System.out.println("contentType==" + this.urlContentType); System.out.println("fileName==" + this.urlFileName); File basePath = new File(ServletActionContext.getServletContext().getRealPath(destPath)); System.out.println(basePath+"根目录============="); if (!basePath.exists()) { basePath.mkdirs(); } String fileEx = urlFileName.substring(urlFileName.indexOf("."), urlFileName.length()); String fileRealName = urlFileName.substring(0,urlFileName.indexOf(".")) + String.valueOf(new Date().getTime()) + fileEx; copy(url, new File(basePath.getCanonicalPath() + "/" + urlFileName)); Loadcate loadcate = uploadService.getLoadcateIdByTitle(loadcateName); upload.setLoadcate(loadcate); upload.setLoadcateId(upload.getLoadcate().getLoadcate_id()); //保存关系 upload.setUpload_time(new Date()); //上传时间为当前时间 upload.setUrl(fileRealName); //修改传的文件名 uploadService.saveUpload(upload); return SUCCESS; } //文件的读取 public void copy(File srcFile, File destFile) throws IOException { BufferedInputStream bis = null; BufferedOutputStream bos = null; try { bis = new BufferedInputStream(new FileInputStream(srcFile)); bos = new BufferedOutputStream(new FileOutputStream(destFile)); byte[] buf = new byte[8192]; for (int count = -1; (count = bis.read(buf)) != -1;) { bos.write(buf, 0, count); } bos.flush(); } catch (IOException ie) { throw ie; } finally { if (bis != null) { bis.close(); } if (bos != null) { bos.close(); } } } }
<form action="${base}/upload/saveUpload.action" method="post" enctype="multipart/form-data" > <input type="file" name="url" style=" 300px"/> </form>