SSH--文件上传、删除

2019-04-15 14:16发布

public String execute(){ //获取当前web工程下的/pic目录的在本机的绝对路径,如果没有则自动创建 String targetPath = ServletActionContext.getServletContext().getRealPath("/pic"); //重新设置文件名字,非必须 String targetFileName = generateFileName(fileFileName); File targetFile = new File(targetPath, targetFileName); try { FileUtils.copyFile(file, targetFile); session.put("filePath", "pic/"+targetFileName); } catch (IOException e) { System.out.println("文件上传失败!"); return "reUpload"; } return "success"; } public String generateFileName(String fileName){ String formateDate = new SimpleDateFormat("yyMMddHHmmss").format(new Date()); int random = new Random().nextInt(10000); int position = fileName.lastIndexOf("."); String subStr = fileName.substring(position); return formateDate+random+subStr; }

文件类型、文件名字命名规则:
private File file ; private String fileFileName; private String fileContentType;File的对象名+FileName; File的对象名+ContentType
jsp页面:


删除..................................... /* * 删除web项目下的文件 */ public void deleteWebFile(String fileName){ String targetPath = ServletActionContext.getServletContext().getRealPath("/pic"); fileName = fileName.substring(fileName.lastIndexOf("/")); File file = new File(targetPath,fileName); //拼凑模型:D:myeclipse1workspace.metadata.me_tcat7webappsXPMpic/1710121639414792.jpg if(file.exists()){ file.delete(); } }