struts文件上传保存

  • 引入js文件
<script src="/js/wxMgt/jquery-3.3.1.js"></script>
  • jsp页面代码
 <body>
  	<p>文件上传</p>
  	<form id="form">
  		<input id ="fileUpload" name="file" type="file"/>
  	</form>
  	<button id="upload">确认上传</button>
  </body>
  • js代码
<script type="text/javascript">
  	$("#upload").click(function(){
  		var formData = new FormData(document.getElementById("form"));
  		$.ajax({
  			url:"/wxMgt_fetAttach.action",
  			type:'POST',
  			data:formData,
  			contentType: false,
  			processData: false,
  			done : function(e, data) {
  			
  			}
  		});
  	})
  </script>
  • 后端接收文件
public void fetAttach() throws IOException{//这里的file必须有get/set方法
		String path = readProperties("uploadPath");//读取配置文件的路径
		String realpath = ServletActionContext.getServletContext().getRealPath(path);//获取绝对路径
		File f = new File(realpath);
        if (!f.exists()) {//判断该文件夹是否存在/无则创建
            f.mkdirs();
        }
        File save = new File(realpath+"\\save.docx");//新建文件
		FileUtils.copyFile(file, save);//文件上传后会保存在Tomcat\cciditOA\work\Catalina\localhost\_  的路径下,将该临时文件保存在上面的路径下
	}
上一篇:文件上传和下载


下一篇:文件下载