本想利用Ajax實現無刷新文件上傳,后來發現不易實現,在網上找了很久,終于找到一個“偽AJAX”的實現方式,現在發出來我實際的代碼,一饗讀者。
首先我們需要一個上傳的HTML或者jsp文件,如下:
<FORM METHOD="POST" ACTION="../servlet/FileUploadServlet" enctype="mult <input type="file" name="sfile" style="width:450">
<input type="hidden" name="act" value="upload">
<INPUT type="submit" value="上傳文件"><span id="msg"></span>
<br>
<font color="red">支持JPG,JPEG,GIF,BMP,SWF,RMVB,RM,AVI文件的上傳</font>
<iframe name='hidden_frame' id="hidden_frame" style='display:none'></iframe>
</form>
其中FORM的TARGET屬性[b]非常重要[/b],把FORM的ACTION提交到一個隱藏的IFRAME中去執行,然后返回的時候在MSG的地方填入操作即可,SERVLET的類似代碼如下:
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException{
PRintWriter out = response.getWriter();
response.setCharacterEncoding("utf-8");
response.setHeader("Charset","utf-8");
response.setHeader("Cache-Control", "no-cache");
String filepath="",msg="",ext="";
SmartUpload su = new SmartUpload();
boolean succ=true;
。。。。。。
try{
su.initialize(getServletConfig(),request,response);
su.setMaxFileSize(102400000);
su.setTotalMaxFileSize(102400000);
su.setAllowedFilesList(mediaExt+","+FlashExt+","+imgExt);
su.setDeniedFilesList("exe,bat,,");
su.upload();
for (int i=0;i<su.getFiles().getCount();i++)
{
com.jspsmart.upload.File file = su.getFiles().getFile(i);
if (file.isMissing()) continue;
String fileName=UploadFileUtils.returnRandomFileName(file.getFileExt());
ext=file.getFileExt().toLowerCase();
。。。。。。。。。。。
msg="<a href=/"#/">上傳成功!</a>";
}
}catch(SmartUploadException sue){
succ=false;
msg="<font color=red>上傳失?。赫垯z查文件擴展名或文件大??!</font>";
}catch(Exception ex){
succ=false;
msg="<font color=red>上傳失?。赫垯z查文件擴展名或文件大??!</font>";
ex.printStackTrace();
}
msg=Escape.escape(msg);
if(succ)
out.println("parent.document.getElementById('msg').innerHTML = unescape('"+msg+"');parent.backCallIframe('"+Escape.escape(ext)+"','"+Escape.escape(filepath)+"')");
else
out.println("parent.document.getElementById('msg').innerHTML = unescape('"+msg+"');");
out.close();
}
新聞熱點
疑難解答