SSH文件上传代码片段

2018-06-18 02:31:24来源:未知 阅读 ()

新老客户大回馈,云服务器低至5折

一、文件上传限制:

在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 }

 

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:玩转log4j

下一篇:Java:异常处理