I wanted to use ajax (static dynamic website) to upload a non-refreshing file. Later I found it difficult to implement it. After searching for it online for a long time, I finally found a "pseudo ajax (static dynamic website) "implementation method, now I am sending out the actual code, a reader.
First, we need an uploaded HTML or jsp (preferred for SUN Enterprise Applications) file, as shown below:
<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, and AVI files. </font>
<Iframe name = hidden_frame id = "hidden_frame" style = display: none> </iframe>
</Form>
The TARGET attribute of FORMVery important, Submit the form action to a hidden IFRAME for execution, and enter the operation in the MSG field when returning the result. The SERVLET code is similar to the following:
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. jsp (preferred for SUN Enterprise Applications) smart. 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: Check the file extension or file size! </Font> ";
} Catch (Exception ex ){
Succ = false;
Msg = "<font color = red> Upload Failed: Check the file extension or file size! </Font> ";
Ex. printStackTrace ();
}
Msg = Escape. escape (msg );
If (succ)
Out. println ("parent.doc ument. getElementById (msg ). innerHTML = unescape ("+ msg +"); parent. backCallIframe ("+ Escape. escape (ext) + "," + Escape. escape (filepath) + ")");
Else
Out. println ("parent.doc ument. getElementById (msg). innerHTML = unescape (" + msg + ");");
Out. close ();
}