一、文件上传限制:

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

SSH文件上传代码片段-LMLPHP

二、controller代码

 @Namespace("/")
@ParentPackage("struts-default")
@Scope("prototype")
@Controller
public class ImageAction extends ActionSupport { private File imgFile; public void setImgFile(File imgFile) {
this.imgFile = imgFile;
}
private String imgFileFileName; public void setImgFileFileName(String imgFileFileName) {
this.imgFileFileName = imgFileFileName;
} @Action(value = "imageAction_upload")
public String upload() throws IOException {
Map<String,Object> map = new HashMap<>();
try { String dirPath = "/upload/";
ServletContext servletContext = ServletActionContext.getServletContext();
String realPath = servletContext.getRealPath(dirPath); String suffix = imgFileFileName.substring(imgFileFileName.lastIndexOf("."));
String fileName = UUID.randomUUID().toString().replaceAll("-","")+suffix;
File destFile = new File(realPath+"/"+fileName); FileUtil.copyFile(imgFile,destFile); String contextPath = ServletActionContext.getServletContext().getContextPath(); map.put("error",0);
map.put("url",contextPath+dirPath+fileName); } catch (IOException e) {
map.put("error",1);
map.put("message",e.getMessage());
e.printStackTrace();
}
String json = JSONObject.fromObject(map).toString();
HttpServletResponse response = ServletActionContext.getResponse();
response.setContentType("text/html;charset=UTF-8");
response.getWriter().write(json); return NONE;
}
}
05-29 00:18