I originally wanted to use AJAX to upload files without refreshing, but later found that it was not easy to implement. After searching online for a long time, I finally found a "pseudo-AJAX" implementation. Now I will post my actual code for readers.
First we need an uploaded HTML or JSP file, as follows:
<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="Upload file"><span id="msg"></span>
<br>
<font color="red">Supports uploading JPG, JPEG, GIF, BMP, SWF, RMVB, RM, AVI files</font>
<iframe name='hidden_frame' id="hidden_frame" style='display:none'></iframe>
</form>
Among them, the TARGET attribute of FORM [b] is very important [/b]. Submit the ACTION of FORM to a hidden IFRAME for execution, and then fill in the operation in the MSG when returning. The similar code of SERVLET is as follows:
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="#">Upload successful!</a>";
}
}catch(SmartUploadException sue){
succ=false;
msg="<font color=red>Upload failed: Please check the file extension or file size!</font>";
}catch(Exception ex){
succ=false;
msg="<font color=red>Upload failed: Please check the file extension or file size!</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();
}