jsp版ajax文件上传

jsp版ajax文件上传

 
jsp利用ajax + jquery无刷新上传图片方法
第一步导入需要用到的包,jquery.js,ajaxfileupload.js ,到 http://www.phpletter.com去下载ajaxfileupload包
HTML代码如下
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
   <title>Ajax无刷新上传文件</title>
       <!-- 引入相关的js文件,相对路径   -->
       <script type="text/javascript" src="js/jquery.js"></script>
       <script type="text/javascript" src="js/ajaxfileupload.js"></script>
       <script type="text/javascript">
       function ajaxFileUpload(){
               $.ajaxFileUpload({
                 url:'image.do?stats=uploadImage',             //需要链接到服务器地址
                 secureuri:false,
                 fileElementId:'editorImg',                         //文件选择框的id属性
                 dataType: 'text',                                     //服务器返回的格式,可以是json
                 success: function (data, status)             //相当于java中try语句块的用法
                 {  
                 alert(data);       //data是从服务器返回来的值  
                     $('#result').html('上传图片成功');
                 },
                 error: function (data, status, e)             //相当于java中catch语句块的用法
                 {
                     $('#result').html('上传图片失败');
                 }
               }
             );
           }
</script>
</head>
       <body>
           <form name="padd" id="padd" enctype="multipart/form-data">
                 <input type="file" id="editorImg" name="editorImg"/>
                 <input type="button" onclick="ajaxFileUpload();" value="上传">
         </form>
<div id="result"></div>
</body>
</html>
后台接收我用的是Struts自代的上传组件进行上传,Struts的配值就不用说了,代码如下
//Form类
public class ProductForm extends ActionForm {
             //这要与HTML页面的file id相同
             private FormFile editorImg;
             public FormFile getEditorImg() {
                     return editorImg;
             }
             public void setEditorImg(FormFile editorImg) {
                     this.editorImg = editorImg;
             }
}
//Action类
public class ProductAction extends DispatchAction{
             public ActionForward uploadImage(ActionMapping mapping, ActionForm form,
             HttpServletRequest request, HttpServletResponse response)
             throws Exception {
                   response.setContentType("text/html;charset=GBK");
                   //获取当前项目在Tomcat中的路径
                 String path = request.getSession().getServletContext().getRealPath("images");
                 ProductForm pf = (ProductForm)form;
                 FormFile file = pf.getEditorImg();
                 FileOutputStream fos = new FileOutputStream(path + "/" + file.getFileName());
                 //将文件写入指定路径
                 fos.write(file.getFileData());
                 fos.flush();
                 fos.close();
                 PrintWriter out = response.getWriter();
                 out.println(file.getFileName());
                 return null;
           }
}

你可能感兴趣的:(Ajax)