当前位置: 代码迷 >> Ajax >> jquery+struts1.3.8的ajax下传文件
  详细解决方案

jquery+struts1.3.8的ajax下传文件

热度:843   发布时间:2012-09-29 10:30:01.0
jquery+struts1.3.8的ajax上传文件
最近做项目,对用户体验要求较高,大量采用jquery的ajax支持,最近要做个文件上传,要求也用ajax方式实现,这里采用了jquery的ajaxfileupload.js插件。见附件

1.上传jsp。

<table cellpadding="0" cellspacing="0" border="0" class="ktable_9" >
        <tr>
            <td><input type="file" name="upoadFileName" id="upoadFileName"><a  href="#" onclick="uploadFile();return false;"><span><span>上传</span></span></a></td>
            </tr>
            <tr>
            <td>&nbsp;</td>
            </tr>
        </table>

2.下面是前端的js脚本:

function uploadFile(){
                var myurl="/uploadMyFile.do?tenderInfoId="+tenderInfoId;
         jQuery.ajaxFileUpload(
                   {
                url:myurl,          
                secureuri:false,
                            fileElementId:'imgFile',   --上传文件对应的文本域的id                    
                dataType: 'json',                                    
                success: function (data, status)          
                {    
                    alert('上传成功');
                                  },
                error: function (data, status, e)           
                {
                   alert('上传失败');
                }
            } );
    }


3.这是后台的action:
public ActionForward uploadMyFile(ActionMapping mapping,
ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
/* =============禁止缓存============== */
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Expires", "0");
/* =============禁止缓存============== */
response.setContentType("text/html;charset=UTF-8");

String filewholeName = "";
try {
CompanyApplyDTO applyDTO = (CompanyApplyDTO) form;
  // FormFile formfile =  applyDTO.getImgFile();
//--这种方式也可以,但CompanyApplyDTO 中应该有 一个这样的属性FormFile  imgFile;

    FormFile formfile = (FormFile) applyDTO.getMultipartRequestHandler()
.getFileElements().get("imgFile");
//--上传文件对应的文本域的id                    
String fileName = file.getFileName();
String fileSimpleName = fileName.substring(fileName
.lastIndexOf("."));
fileName = DateHandler.convertStringToDate(new Date(), null)
+ fileName;

if (file.getFileSize() > 50 * 1024 * 1024) {
write("{'result':false,'error':' filesize'}", response);
return null;
}
String uploadPath = this.getServlet().getServletContext()
.getRealPath("/")
+ "uploadfile/";
File savePath = new File(uploadPath);
System.out.println(savePath.getAbsolutePath());
if (!savePath.exists()) {
savePath.mkdir();
}
filewholeName = uploadPath + "/" + fileName;
FileOutputStream fos = new FileOutputStream(filewholeName);
fos.write(file.getFileData());
log.info("#############上传文件:" + fileName);
write("{'result':true}", response);
} catch (Exception e) {
write("{'result':false,'error':'" + e.getMessage() + "'}", response);
}
return null;
}
说明:

jaaxfileupload.js有可能执行错误,在接受返回值后,刚可将代码中
原为 :  eval("data =  "+data+ );  替换为如下:
eval("data = \" "+data+" \" ");


原代码基于jquery 低版本,1.4.2之前, 在高版本jquery中执行会有错误,handleError函数在高版本中已经没有,需做相关处理,最简单是从jquery1.4.2中移植到这里。

    eval("data = \" "+data+" \" ");

在springmvc中我如下返回 :  out.write("{'success':'1'}");现在
如下方式接收返回值没问题。
$.ajaxFileUpload({ 
        url: saveurl, 
        secureuri:false, 
        fileElementId:'advertResource', 
        dataType: 'json', 
        data: {//加入的文本参数 
            "advertType":myadvertType,  //广告类型
            "advertisingName":$('#advertisingName').val(),
            "beginDate":$('#beginDate').val(),
            "endDate":$('#endDate').val(),
            "eneityId":publisherId,
         //   "myurl":advertInfourl,
            "picType":picType,
            "location":advertTotal+1
        }, 
        success: function(data,status) {
        if(data.success=='1'||data.success==1){
        isAddFlag=true;
            closeAddDiv();
            alert("添加广告成功!");
            advertTotal+=1;
        }else{
        alert("添加广告失败!");
        }
        }, 
        error: function(data, status, e) { 
            alert("系统异常,添加 广告信息失败!");
            closeAddDiv();
         } 
    }); 

springmvc后台controller代码:这里除了上传文件外,还有自定义的其他参数。
只需要简单修改ajaxfileupload.js,就可以了。

@RequestMapping(value="/addAdvertInfo")
/*@ResponseBody*/
public void addAdvertisingInfo(HttpServletRequest request, HttpServletResponse response) {
PrintWriter out=null;
try {
out = response.getWriter();
boolean isUpload = ServletFileUpload.isMultipartContent(request);
if (isUpload) {
AdvertisingInfoPO advertObj = new AdvertisingInfoPO();
advertObj.setAdvertisingName(request
.getParameter("advertisingName"));
advertObj.setEntity(request.getParameter("eneityId"));
advertObj.setLocation(request.getParameter("location"));
//advertObj.setUrl(request.getParameter("myurl"));
advertObj.setType(Integer.parseInt(request
.getParameter("advertType")));
advertObj.setBeginDate(DateFormatUtil.parser("yyyy-MM-dd",
request.getParameter("beginDate")));
advertObj.setEndDate(DateFormatUtil.parser("yyyy-MM-dd",
request.getParameter("endDate")));

advertObj.setAdvertId(KeyUtil.getID());
             
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
CommonsMultipartFile mfile = (CommonsMultipartFile) multipartRequest.getFile("advertResource");
advertObj.setResource(mfile.getBytes());
advertObj.setResourceType(request.getParameter("picType"));
advertisingInfoService.create(advertObj);
}
} catch (Exception e) {
log.error("addAdvertisingInfo:添加广告信息失败。", e);
out.write("{'success':'0'}");
e.printStackTrace();
}
  out.write("{'success':'1'}");
}
1 楼 BGX5810 2012-03-03  
试试看把“dataType: 'json', ”换成“dataType: 'text', ”,我是这么解决的
  相关解决方案