SSH文件上传代码片段

一、文件上传限制:

在web.xml中配置Struts前端控制器时,设置初始化参数:如下图所示

二、controller代码

 1 @Namespace("/")
 2 @ParentPackage("struts-default")
 3 @Scope("prototype")
 4 @Controller
 5 public class ImageAction extends ActionSupport {
 6 
 7     private File imgFile;
 8 
 9     public void setImgFile(File imgFile) {
10         this.imgFile = imgFile;
11     }
12     private String imgFileFileName;
13 
14     public void setImgFileFileName(String imgFileFileName) {
15         this.imgFileFileName = imgFileFileName;
16     }
17 
18     @Action(value = "imageAction_upload")
19     public String upload() throws IOException {
20         Map<String,Object> map = new HashMap<>();
21         try {
22 
23             String dirPath = "/upload/";
24             ServletContext servletContext = ServletActionContext.getServletContext();
25             String realPath = servletContext.getRealPath(dirPath);
26 
27             String suffix = imgFileFileName.substring(imgFileFileName.lastIndexOf("."));
28             String fileName = UUID.randomUUID().toString().replaceAll("-","")+suffix;
29             File destFile = new File(realPath+"/"+fileName);
30 
31             FileUtil.copyFile(imgFile,destFile);
32 
33             String contextPath = ServletActionContext.getServletContext().getContextPath();
34 
35             map.put("error",0);
36             map.put("url",contextPath+dirPath+fileName);
37 
38 
39         } catch (IOException e) {
40             map.put("error",1);
41             map.put("message",e.getMessage());
42             e.printStackTrace();
43         }
44         String json = JSONObject.fromObject(map).toString();
45         HttpServletResponse response = ServletActionContext.getResponse();
46         response.setContentType("text/html;charset=UTF-8");
47         response.getWriter().write(json);
48         
49         return NONE;
50     }
51 }

 

posted @ 2018-03-26 16:26  gdwkong  阅读(524)  评论(0编辑  收藏  举报