S2SH 利用ajaxfileupload实现图片无刷新上传

首先 jsp页面:

导入   

<script src="js/jquery-2.1.1.js" type="text/javascript"></script>

<script src="js/ajaxfileupload.js" type="text/javascript"></script>

js代码:

<script type="text/javascript">
        function ajaxFileUpload() {
            //alert("aa");
            $.ajaxFileUpload
            (
                {
                    url: 'ajaxUpload.action', //用于文件上传的服务器端请求地址
                    secureuri: false, //是否需要安全协议,一般设置为false
                    fileElementId: 'file1', //文件上传域的ID
                    dataType: 'text', //返回值类型 一般设置为json;注: 用json返回有点问题,这里用text返回存字符串
                    
                    success:function(data)
                    {                        
                        $("#img1").attr("src", data);
                        //alert(data.message);
                    },
                    error: function (data, status, e)//服务器响应失败处理函数
                    {
                        alert(e);
                    }
                }
            );
            return false;
        }
    </script>

body代码:

    <body>
        <p><input type="file" id="file1" name="file1" /></p>
        <input type="button" value="上传" οnclick="return ajaxFileUpload()"/>
        <p><img id="img1" alt="这是图片" src="" /></p>
    </body>


struts.xm代码:

</pre><pre name="code" class="java"><action name="ajaxUpload" class="AdminAction" method="ajaxUpload"></action>

后台action代码:

  

  private File file1;    //file1 对应jsp页面的file的name
    private String file1FileName;    
    private String file1ContentType; 

    //实现get和set......

    public void ajaxUpload() throws Exception {
        HttpServletResponse response = ServletActionContext.getResponse();
        response.setContentType("text/html; charset=UTF-8");  //因为使用text类型,所以用text/html
        String message = null;
        String path = ServletActionContext.getServletContext().getRealPath("/photo"); //获得服务器下的photo路径
        try {  
            File f = this.getFile1();  
            FileInputStream inputStream = new FileInputStream(f);  
            FileOutputStream outputStream = new FileOutputStream(path + "/"+ this.getFile1FileName()); 

            //存储图片

            byte[] buf = new byte[1024];  
            int length = 0;  
            while ((length = inputStream.read(buf)) != -1) {  
                outputStream.write(buf, 0, length);  
            }  
            inputStream.close();  
            outputStream.flush();  
            message = "http://localhost:8080/xxx/photo/"+this.getFile1FileName();   //返回的数据--图片的显示地址
        } catch (Exception e) {  
            e.printStackTrace();  
            message = "上传异常!!!!";  
        }
        
        response.getWriter().print(message);
    }



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值