首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > Ajax >

ajax jQuery 实现文件下传

2012-09-09 
ajax jQuery 实现文件上传1.上传jsp。 table cellpadding0 cellspacing0 border0 trtdinpu

ajax jQuery 实现文件上传



1.上传jsp。

<table cellpadding="0" cellspacing="0" border="0" >
        <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:""upoadFileName"",   --上传文件对应的文本域的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");
TTenderFileDTO tendform = (TTenderFileDTO) form;

MultipartHttpServletRequest mhs = (MultipartHttpServletRequest) request;
MultipartFile mf = mhs.getFile("batchSearchFile");

String filewholeName = "";
try {
FormFile file = (FormFile) tendform.getMultipartRequestHandler()
.getFileElements().get("upoadFileName");--对应于前端的文本域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;
}

热点排行