<script type="text/javascript">
function ajaxFileUpload()
    {
        
        $.ajaxFileUpload({
                url:'upload.action',//用于文件上传的服务器端请求地址
                secureuri:false,//一般设置为false
                fileElementId:'upload',//文件上传控件的id属性  <input type="file" id="upload" name="upload" />
                dataType: 'json',//返回值类型 一般设置为json
                success: function (data, status)  //服务器成功响应处理函数
                {
                    alert(data.message);//从服务器返回的json中取出message中的数据,其中message为在struts2中action中定义的成员变量
                    $("#img").attr("src",data.imagePath);
                    if(typeof(data.error) != 'undefined')
                    {
                        if(data.error != '')
                        {
                            alert(data.error);
                        }else
                        {
                            alert(data.message);
                        }
                    }
                },
                error: function (data, status, e)//服务器响应失败处理函数
                {
                    alert(e);
                }
            });
        return false;
    }
</script>
<input type="file" id="upload" name="upload" />
        <input type="button" value="上传" onclick="return ajaxFileUpload();">
private File upload;
private String uploadFileName;
private String uploadFileContentType;
private String message = "成功上传文件";
private String imagePath; public String execute() throws Exception {
String path = ServletActionContext.getRequest().getRealPath("/upload"); try {
File file = this.getUpload();
if (!this.getUploadFileName().endsWith(".jpg")) {
message = "上传的文件格式只能为.jpg格式";
return ERROR;
}
FileInputStream in = new FileInputStream(file);
imagePath="upload/"+ this.getUploadFileName();
FileOutputStream out = new FileOutputStream(path + "\\"+ this.getUploadFileName());
byte[] b = new byte[1024];
int length = 0;
while ((length = in.read(b)) != -1) {
out.write(b, 0, length);
}
in.close();
out.close();
} catch (Exception e) {
e.printStackTrace();
message = "上传文件失败,请联系管理员";
}
return SUCCESS;
}
<package name="upload" extends="json-default">
        <action name="upload" class="org.xx.xx.action.xAction">
            <result type="json" name="success">
                <param name="contentType">text/html</param>
            </result>
            <result type="json" name="error">
                <param name="contentType">text/html</param>
            </result>
        </action>
    </package>
action中的get、set方法自己补上就可以了。

解决方案 »

  1.   


    我的file框 id和name是变动的,主要是这个问题想请教下
      

  2.   


    我的file框 id和name是变动的,主要是这个问题想请教下
    变动还不简单?调用ajaxFileUpload(id,name)方法的时候把Id,name什么值都传过去不就得了。
      

  3.   


    我的file框 id和name是变动的,主要是这个问题想请教下
    变动还不简单?调用ajaxFileUpload(id,name)方法的时候把Id,name什么值都传过去不就得了。主要我的name 和id是file[%{#status.index}]这样的形式,在s:iterator标签下的,怎么书写呢,普通button的onclick="ajaxFileUpload();"中 无法传入这种形式的变量值
      

  4.   

    onclick="ajaxFileUpload(‘%{#status.index}’ );" />
      

  5.   


    解析出来源代码显示onclick="ajaxFileUpload('%{#status.index}');还是这样,参数没穿进去
      

  6.   

    回复于: 2014-03-13 13:59:18
    onclick="ajaxFileUpload(‘%{#status.index}’ );" />   报错贴出来,
      

  7.   

      jsp页面没报错,只是我运行该页面看源代码,发现%{#status.index}没传进去
      

  8.   

    ajaxFileUpload的fileElementId是不固定的 每个上传框对应一个id,那后台的action中File字段属性又该如何定义去对应呢,求解答
      

  9.   

    用<s:property value="" />试下
      

  10.   

    用<s:property value="" />试下不行
      

  11.   

    用<s:property value="" />试下不行值是一定可以通过struts标签传给js的方法的,有很多种传值的方式,你 多试几种。
      

  12.   


    现在有个问题就是 我每次传给ajaxFileUpload的fileElementId是不固定的 每个上传框对应一个id,那后台的action中File字段属性又该如何定义去对应呢,求解答 
      

  13.   

    不太理解你的意思,按我的理解,你好像是想上传好几个图片。
    我这几天也在弄这个上传图片。
    我的做法是每个file文本框点击选择文件后,就发送一个上传请求,把选择的文件上传。
    我的代码:<img id="pic01" src="image/addpic.png" width="100" height="100" style="border-width:1px;border-style:solid;" onclick="document.getElementById('file01').click();"/>
    <input type="file" name="file01" id="file01" style="display:none;" onchange="return ajaxFileUpload('file01');"/>
    你的可以写成:
    <s:file name="file[%{#status.index}]"  id="file[%{#status.index}]" onchange="ajaxFileUpload(‘file[%{#status.index}]’);"/>
       function ajaxFileUpload (fileid){
    $.ajaxFileUpload ({
    url :'xxx.do?fileId=' + fileid,
    type:"POST",
    secureuri :false,
    accept:"application/json",
    fileElementId :fileid,
    success : function (data, status, e){
    //...
    },
    error: function (data, status, e){
    alert(e);
    }
    })
    }action里可以类似这样写:public String uploadPhoto (HttpSession session, HttpServletRequest request, String fileId){
    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
    MultipartFile photo = multipartRequest.getFile(fileId);
                    ......
      

  14.   

    以下是我Action中的代码
    public class UploadAction extends ActionSupport { private static final long serialVersionUID = 1L;
    private File fileid;
    private String fileFileName;
    private String fileFileContentType;
    private String message = "上传成功";
    private String userName;
    private String dataName;
    private String datapath;
    public String upload() throws Exception {
    String path = ServletActionContext.getRequest().getSession().getServletContext().getRealPath("/upload");
    String[] imgTypes = new String[] { "gif", "jpg", "jpeg", "png","bmp" };
    String savePath=path+File.separator+this.getUserName();
    File dirFile = new File(savePath);
     if (!dirFile.exists()) {
         dirFile.mkdirs();
     }
    try {
       File f = this.getFileid();
       
       String fileExt = this.getFileFileName().substring(this.getFileFileName().lastIndexOf(".") + 1).toLowerCase();

       if (!Arrays.<String> asList(imgTypes).contains(fileExt)) {
        message="只能上传gif,jpg,jpeg,png,bmp格式的图片文件";
        return ERROR;
       }
       datapath=savePath+File.separator+this.getFileFileName();
       FileInputStream fis = new FileInputStream(f);
       FileOutputStream fos = new FileOutputStream(datapath);
       IOUtils.copy(fis, fos);  
         fos.flush();
             fos.close();
             fis.close();
      } catch (Exception e) {
       e.printStackTrace();
       message = "上传失败";
      }
      return SUCCESS;
     }
    每次上传提示找不到文件,是不是fileid没对应上