jQuery插件AjaxFileUpload实现ajax文件上传

最新要给项目加一个图片上传功能,搞了很久,经历了一些波折,最终搞好。

要用ajax,最开始想到的是如下:

html代码:

<body>
    <form action="uploadpicture" id="imageForm" enctype="multipart/form-data" method="POST">  
        <input type="file" name="picture" id=picture>  
        <input type="button" onclick="uploadpicture();" value="上传">   
    </form>
</body>

js代码:

function uploadpicture() {
            var picture=$("#picture").val();
             $.ajax({
                url:'uploadpicture',
                type:'post',
                //processData:'false',
                contentType:'multipart/form-data',
                cache : false,
                dataType:'json',
                data:{picture:picture},
                success:function(){
                    window.location.href="index.jsp";
                }
            });
         }

但这只适合客户端和服务端在同一台机器上,因为picture=$(“#picture”).val();得到的是文件的路径+名称,而不是文件的内容。

其实用form的表单提交很容易实现:

html代码:

<body>
    <form action="uploadpicture" id="imageForm" enctype="multipart/form-data" method="POST">  
        <input type="file" name="picture" id=picture>  
        <input type="submit" value="上传">   
    </form>
</body>

后台接收请求的java代码:

@RequestMapping(value="uploadpicture",method={RequestMethod.POST,RequestMethod.GET})
    public @ResponseBody void testpic(HttpServletRequest request,HttpServletResponse response) throws JSONException, IOException
    {
        MultipartHttpServletRequest request2 = (MultipartHttpServletRequest)request;
        MultipartFile pi=request2.getFile("picture");

        FileOutputStream out = new FileOutputStream("C:/Users/wyz/test.jpg");
        InputStream in1=pi.getInputStream();
        byte[] by = new byte[1024];
        int len = 0;
        while((len=in1.read(by))!=-1){
            out.write(by, 0, len);
        }
        out.close();
        in1.close();
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("result", "yes");
        response.getOutputStream().write(jsonObject.toString().getBytes("utf-8"));
     }

@RequestMapping(value="uploadpicture1",method={RequestMethod.POST,RequestMethod.GET})
    public @ResponseBody void testpic1(@RequestParam("picture") MultipartFile file, HttpServletRequest request,HttpServletResponse response) throws JSONException, IOException
    {
        FileOutputStream out = new FileOutputStream("C:/Users/wyz/test1.jpg");
        InputStream in1=file.getInputStream();
        byte[] by = new byte[1024];
        int len = 0;
        while((len=in1.read(by))!=-1){
            out.write(by, 0, len);
        }
        out.close();
        in1.close();
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("result", "yes");
        response.getOutputStream().write(jsonObject.toString().getBytes("utf-8"));
     }

都可以实现将接收到的图片存储在C:/Users/wyz/目录下。注意form中的action请求要和java代码对应,分别是uploadpicture和uploadpicture1.

但是,项目要求不能刷新页面,所以还是要用ajax异步请求来处理


html代码:(和文章开头的html代码一样)

<body>
    <form action="uploadpicture" id="imageForm" enctype="multipart/form-data" method="POST">  
        <input type="file" name="picture" id=picture>  
        <input type="button" onclick="uploadpicture();" value="上传">   
    </form>
</body>

js代码:
首先要引入jquery和ajaxfileupload代码

<script type="text/javascript" src="resources/js/jquery-1.8.3.min.js"></script>
        <script type="text/javascript" src="resources/js/ajaxfileupload.js"></script>
function uploadpicture() {
            $.ajaxFileUpload({
                url: 'uploadpicture',
                secureuri: false,
               // data: data,
                fileElementId: 'picture',
                dataType: 'json',
                success: function (data) {
                    alert(data.result);

                },
                error: function (data,status,e) {
                    alert(e);
                }
            });
        }

服务端的java代码:

//处理上传的图片
    @RequestMapping(value="uploadpicture",method={RequestMethod.POST,RequestMethod.GET})
    public @ResponseBody void testpic(HttpServletRequest request,HttpServletResponse response) throws JSONException, IOException
    {
        MultipartHttpServletRequest request2 = (MultipartHttpServletRequest)request;
        MultipartFile pi=request2.getFile("picture");

        FileOutputStream out = new FileOutputStream("C:/Users/wyz/test.jpg");
        InputStream in1=pi.getInputStream();
        byte[] by = new byte[1024];
        int len = 0;
        while((len=in1.read(by))!=-1){
            out.write(by, 0, len);
        }
        out.close();
        in1.close();
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("result", "yes");
        response.getOutputStream().write(jsonObject.toString().getBytes("utf-8"));
     }

通过这种方式可以把图片传到服务端,但是总是返回error,说明在$.ajaxFileUpload中返回的是错误,百思不得其解,甚至看了ajaxFileUpload.js的源码,没想错误就在这个源码上面。返回错误如下:

在这篇博客找到问题的答案http://liwx2000.iteye.com/blog/1540321,为防止博客找不到,马上会转载下来。
解决方法:在ajaxFileUpload.js的源码中找到

uploadHttpData: function( r, type ) {
        var data = !type;
        data = type == "xml" || data ? r.responseXML : r.responseText;

        // If the type is "script", eval it in global context
        if ( type == "script" )
            jQuery.globalEval( data );
        // Get the JavaScript object, if JSON is used.
        if ( type == "json" ){
            eval( "data = " + data );
        }

        // evaluate scripts within html
        if ( type == "html" )
            jQuery("<div>").html(data).evalScripts();

        return data;
    },

增加内容,如下:

uploadHttpData: function( r, type ) {
        var data = !type;
        data = type == "xml" || data ? r.responseXML : r.responseText;

        // If the type is "script", eval it in global context
        if ( type == "script" )
            jQuery.globalEval( data );
        // Get the JavaScript object, if JSON is used.
        if ( type == "json" ){
            ////////////以下为新增代码/////////////// 
            data = r.responseText;  
            var start = data.indexOf(">");  
            if(start != -1) {  
              var end = data.indexOf("<", start + 1);  
              if(end != -1) {  
                data = data.substring(start + 1, end);  
               }  
            }  
             ///////////以上为新增代码/////////////// 
           eval( "data = " + data );
        }

        // evaluate scripts within html
        if ( type == "html" )
            jQuery("<div>").html(data).evalScripts();

        return data;
    },

完美解决。
参考
jQuery插件AjaxFileUpload实现ajax文件上传
ajaxFileUpload plugin上传文件 chrome、Firefox中出现SyntaxError:unexpected token <

你可能感兴趣的:(jquery,web上传文件)