Ajax jsp does not need to upload any new files

Source: Internet
Author: User

Ajax jsp does not need to upload any new files
The file upload implemented in this article is also non-page refreshed, it can be said that it is a "AJAX-like" Method

Before the beginning, I would like to say that two sentences are irrelevant. In fact, before the emergence of ajax, web applications can also be refreshing. At that time, most of them were implemented through IFrame. Of course, after the emergence of Ajax, people rushed to the Ajax camp, and iFrame was no longer interesting. However, it is a good choice to use iFrame to upload files without refreshing.

Ps: Ajax technology is basically brought up by google, but IFrame is not used for uploading files in Gmail. Therefore, using IFrame to upload files is the best choice.
The technology I use here is jsp. In fact, asp and php can also be implemented in this way.

 

Html:

 









<Script type = "text/javascript">
Function callback (msg)
{
Document. getElementById ("file"). outerHTML = document. getElementById ("file"). outerHTML;
Document. getElementById ("msg"). innerHTML = "" + msg + "";
}
</Script>

 

 

Java logic processing:

Package com. partner. servlets;

Import java. io. BufferedInputStream;
Import java. io. BufferedOutputStream;
Import java. io. File;
Import java. io. FileOutputStream;
Import java. io. IOException;
Import java. io. PrintWriter;
Import java. util. Date;
Import java. util. Iterator;
Import java. util. List;

Import javax. servlet. ServletException;
Import javax. servlet. http. HttpServlet;
Import javax. servlet. http. HttpServletRequest;
Import javax. servlet. http. HttpServletResponse;

Import org. apache. commons. fileupload. FileItem;
Import org. apache. commons. fileupload. FileUploadException;
Import org. apache. commons. fileupload. disk. DiskFileItemFactory;
Import org. apache. commons. fileupload. servlet. ServletFileUpload;
Import org. apache. commons. fileupload. util. Streams;
Import org. apache. commons. logging. Log;
Import org. apache. commons. logging. LogFactory;

Import com. partner. core. util. UploadConfigurationRead;

Public class FileUploadServlet extends HttpServlet {

Private static final long serialVersionUID = 1L;

Protected final transient Log log = LogFactory. getLog (FileUploadServlet. class );

Protected void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
This. doPost (request, response );
}

@ SuppressWarnings ("unchecked ")
Protected void doPost (HttpServletRequest request, HttpServletResponse response ){
// Directory where the file is stored
// File tempDirPath = new File (request. getSession (). getServletContext (). getRealPath ("/") + File. separator + "uploads ");
String path = UploadConfigurationRead. getInstance (). getConfigItem ("tempPath"). trim ();
File tempDirPath = new File (path );
If (! TempDirPath. exists ()){
TempDirPath. mkdirs ();
}
// Create a disk file Factory
DiskFileItemFactory fac = new DiskFileItemFactory ();

// Create a servlet File Upload Component
ServletFileUpload upload = new ServletFileUpload (fac );

Upload. setHeaderEncoding ("UTF-8 ");
// File list
List fileList = null;
// Parse the request to obtain the File Uploaded from the foreground
Try {
FileList = upload. parseRequest (request );
} Catch (FileUploadException ex ){
Ex. printStackTrace ();
Return;
}
// Saved file name
String imageName = null;
// Conveniently obtain the file list from the front-end
Iterator It = fileList. iterator ();
While (it. hasNext ()){
FileItem item = it. next ();
// If it is not a common form field, it is processed as a file field.
BufferedInputStream in = null;
BufferedOutputStream out = null;
If (! Item. isFormField ()){
ImageName = new Date (). getTime () + "_" + item. getName ();

Try {
In = new BufferedInputStream (item. getInputStream ());
Out = new BufferedOutputStream (
New FileOutputStream (new File (tempDirPath + File. separator + imageName )));
Streams. copy (in, out, true );
} Catch (IOException e ){
Log. error ("File Upload exception:", e );
} Finally {
If (in! = Null ){
Try {
In. close ();
} Catch (IOException e ){
Log. error ("failed to close the input of the uploaded file", e );
}
}
If (out! = Null ){
Try {
Out. close ();
} Catch (IOException e ){
Log. error ("failed to close output of uploaded files", e );
}
}
}
}
}
PrintWriter out = null;
Try {
Out = encodehead (request, response );
} Catch (IOException e ){
E. printStackTrace ();
}
// This place cannot be small; otherwise, the front-end cannot obtain the upload result.

Out. write ("<script> parent. callback ('upload file success ') </script> );
Out. write (imageName );
Out. close ();
}

/**
* Ajax-assisted method for obtaining PrintWriter
* @ Return
* @ Throws IOException
* @ Throws IOException
* Request. setCharacterEncoding ("UTF-8 ");
Response. setContentType ("text/html; charset = UTF-8 ");
*/
Private PrintWriter encodehead (HttpServletRequest request, HttpServletResponse response) throws IOException {
Request. setCharacterEncoding ("UTF-8 ");
Response. setContentType ("text/html; charset = UTF-8 ");
Return response. getWriter ();
}
}

 

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.