开发用的是SSH框架,奈何之前都是SSM
好了,不啰嗦,开始:
1 首先需要下载ajaxfileupload.js文件,百度一搜一堆
function uploadEnclosure(withdrawalsId){ $("#uploadEnclosures").click(); if(confirm("确认上传吗?")){ //选择文件之后执行上传 var imgFile = $("#uploadEnclosures")[0].files[0] $.ajaxFileUpload({ url:'/manager/pay-manager!saveUploadEnclosure.action', secureuri:false, fileElementId:'uploadEnclosures', dataType: 'json', data:{"id":withdrawalsId}, //fileImg:imgFile success: function (data, status) { alert("上传成功!"); var obj = $.parseJSON(data.replace(/<.*?>/ig,"")); alert(obj.fileName); $("#showImg").attr("src", "/WEB-INF/transferAccountsdetail/"+obj.fileName); }, error: function (data, status, e) { alert(e); } }); } return true; } |
result:<pre style="word-wrap: break-word; white-space: pre-wrap;">{"flag":"true"}</pre>
<td > <a οnclick="uploadEnclosure('${pageWithdrawals.id}')" href="#" id="upload">上传</a>  <img id="showImg" alt="" src=""> <a οnclick="#" href="#" id="show">| 查看</a> <input type="file" style="display:none" id="uploadEnclosures" name="imgPath" accept="image/jpg,image/gif,image/png"></input> </td> |
private File imgPath; private String imgPathFileName; private HttpServletRequest request; |
public void saveUploadEnclosure() throws IOException, JSONException{ //设置保存文件路径 String realPath = ServletActionContext.getServletContext().getRealPath("WEB-INF/transferAccountsdetail"); File file = new File(realPath); //测试此抽象路径名表示的文件或目录是否存在。若不存在,创建此抽象路径名指定的目录,包括所有必需但不存在的父目录。 if(!file.exists())file.mkdirs(); try { //保存文件 FileUtils.copyFile(imgPath, new File(file,imgPathFileName)); } catch (IOException e) { e.printStackTrace(); } JSONObject obj = new JSONObject(); obj.put("fileName", imgPathFileName); response.getWriter().print(obj.toJSONString()); } |