由于要使用上传图片功能,附加图片的描述信息, 而传统的<s: file/>因为一些限制在这个小模块中没法使用, 因而搜到了使用ajaxfileupload.js插件进行上传的方法,在使用过程当中,jsp,js,struts2javascript
由于本身不熟悉ajax的状况出了许多的小问题,在这里记录一下, 方便本身查看,也但愿能帮到他人,html
首先说一下思路,经过点击上传直接触发js 的function 调用后台把图片拷贝到指定服务器目录,返回保存的路径到前台,而后跟随图片描述信息一块儿用ajax异步传到后台。(PS:若是有新的方法,麻烦请告知,我只会这个了)java
首先,我先把jsp代码贴上来,jquery
<input type="file" onchange="uploadImage(this)" id="newsImgFile" name="tbslidefile" /> <input type="hidden" id="imgPath" name="imgPath" /> <div class="newlyhead">标题:</div> <div class="newlycontent"><input type="text" class="upload_title" id="slideTitle" name="slideTitle"></div> <input type="button" value="保 存" onclick="saveTwo();" >
记得添加进来须要的js插件,这里我本身写的js叫作index.jsajax
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/ajaxfileupload.js"></script>
<script type="text/javascript" src="js/index.js"></script>chrome
下面是我本身写的js代码apache
function uploadImage(obj) { var fileElementId = "newsImgFile"; //注意这里newsImgFile是上面 input type="file"的 id 若是须要修改记得一块儿修改 $("#newsImgFile").attr('name','file'); //明显.attr就是设置元素的属性值,固然若是单纯上传图片的话能够不用这么麻烦,直接在下面fileElementId:**属性跟input的id name一致就OK了,经过再次转换,能够方便在js中进行不一样图片的控制,固然这里没用到 alert("test"); //只是查看是否执行到了这里,能够去掉 $.ajaxFileUpload({ url:'uploadAction', //须要连接到服务器地址 secureuri:false, fileElementId:fileElementId, //文件选择框的id属性 dataType: 'json', //服务器返回的格式,能够是其余 success: function (response, status, xhr) { //成功后的回调函数 console.log(response.obj); //这个方法能够在浏览器(chrome等)审查元素时候控制台console输出 //alert(response.obj); $('#imgPath').val(response.obj); //这个就是为上面input id="imgPath"赋值,一块儿传到后台 }, error: function (data, status, e) { //至关于java中catch语句块的用法 $('#imgPath').val(''); } }); } function saveTwo() { $.ajax({ type: "post", dataType: "text", contentType:"application/x-www-form-urlencoded; charset=utf-8", url: "addSlide", //都是Action由于是使用struts2框架 data: { slideTitle:$("#slideTitle").val(), slidePath:$("#imgPath").val() }, success: function(response, status, xhr) { console.log(response); //response是返回的值 alert(status); //status是状态,例如success if(status=="success") { jAlert("添加成功!","提示信息"); } else { jAlert("添加失败!","提示信息"); } } }); }
相信上面关于js的说明会很清楚,接下来是后台代码,单纯接收到js上传的图片并返回路径到前面jsjson
package ***** import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.text.SimpleDateFormat; import java.util.Date; import javax.servlet.http.HttpServletResponse; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import org.apache.struts2.ServletActionContext; import com.opensymphony.xwork2.ActionSupport; /** *@author E—mail: *@version create time:2014-6-16上午10:43:43 *class introduce */ public class UploadAction extends ActionSupport { private File file; private String fileFileName; private String savePath; private String obj; /** * 私有变量file要和js中$("#newsImgFile").attr('name','file');一致,这样能够直接接受过来 * 这里是单纯的图片上传到服务器,这个savePath是在struts.xml中配置的 * * */ @Override public String execute() throws Exception { String bigurl = ""; SimpleDateFormat sf = new SimpleDateFormat("yyyyMMddHHmmss"); Date now = new Date(); String dDir = sf.format(now); String fExt = fileFileName.substring(fileFileName.lastIndexOf(".")); String savePath = ServletActionContext.getServletContext().getRealPath(this.getSavePath()); bigurl = savePath+"\\"+dDir + fExt; try { File f = this.getFile(); FileInputStream inputStream = new FileInputStream(f); FileOutputStream outputStream = new FileOutputStream(bigurl); byte[] buf = new byte[1024]; int length = 0; while ((length = inputStream.read(buf)) != -1) { outputStream.write(buf, 0, length); } inputStream.close(); outputStream.flush(); outputStream.close(); } catch (Exception e) { e.printStackTrace(); } //直接是字符串前面就能够接收到,要是跟下面注释同样转换成json前面还要转换,我试过这样能够直接在前面js中response获得, obj =bigurl.substring(bigurl.lastIndexOf("fileResources")) ; // System.out.println("\"success\":true,\"url\":\""+dDir+"/"+fExt+"\",\"bigurl\":\""+bigurl+"\""); // JSONObject jsonobj = JSONObject.fromObject(path); // obj = jsonobj.toString(); return SUCCESS; } public File getFile() { return file; } public void setFile(File file) { this.file = file; } public String getFileFileName() { return fileFileName; } public void setFileFileName(String fileFileName) { this.fileFileName = fileFileName; } public String getSavePath() { return savePath; } public void setSavePath(String savePath) { this.savePath = savePath; } public String getObj() { return obj; } public void setObj(String obj) { this.obj = obj; } }
至于传图片路径和图片标题到后台,获得并保存,就是淡出的struts2后台处理,就不必贴出来了,浏览器
struts.xml中配置这个Action服务器
<action name="uploadAction" class="com.gt.***.action.UploadAction" > <param name="savePath">/fileResources/imageFile</param> <result name="success" type="json"> <param name="contentType"> text/html </param> </result> </action>
至于为何param是这样的,我没仔细深究,若是有朋友知道麻烦告诉我,谢谢。
另外ajaxfileupload.js插件很好得到,百度一下你就能够哈哈。