学导网 >> it000 >> jsp
jsp无刷新文件上传的实现
www.xuedao.net  2007-8-1 11:08:00 互联网

    本想利用AJAX实现无刷新文件上传,后来发现不易实现,在网上找了很久,终于找到一个“伪AJAX”的实现方式,现在发出来我实际的代码,一飨读者。

    首先我们需要一个上传的HTML或者JSP文件,如下:

    <FORM METHOD="POST" ACTION="../servlet/FileUploadServlet" enctype="multipart/form-data" target="hidden_frame" onSubmit="showmsg();" style="margin:0;padding:0">
    <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= idden_frame id="hidden_frame" style= isplay: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(); 
    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>上传失败:请检查文件扩展名或文件大小!</font>";
    }catch(Exception ex){
    succ=false;
    msg="<font color=red>上传失败:请检查文件扩展名或文件大小!</font>";
    ex.printStackTrace();
    }
    msg=Escape.escape(msg);
    if(succ)
    out.println("parent.document.getElementById( sg .innerHTML = unescape( +msg+");parent.backCallIframe( +Escape.escape(ext)+"  "+Escape.escape(filepath)+" ");
    else
    out.println("parent.document.getElementById( sg .innerHTML = unescape( +msg+" ;");
 out.close();
 }

评论】 【关闭
相关新闻
Google提供广告