Ajax jsp no refresh upload file

Source: Internet
Author: User
Tags log log

This article implements the file upload is also no page refresh, can be said to be an "Ajax-like" approach

Before starting to say a few words, in fact, before the advent of Ajax, Web applications can also be non-refreshing, then mostly through the IFRAME to do this. Of course, after the advent of Ajax, people swarm to the Ajax camp, the IFrame is no more. But it's really a good choice to use an IFrame to upload files without a flush.

Ps:ajax technology can basically be said to be brought up by Google, but less Gmail upload files or iframe, so using an IFrame to upload files is the best choice.
I am here to use the technology is JSP, in fact, asp,php, and so on is the same can be achieved

Html:

<body>

<form action= "/fileuploadservlet" id= "Form1" Name= "Form1" enctype= "Multipart/form-data" method= "POST" target= " Hidden_frame ">
<input type= "File" id= "file" name= "file" style= "width:450" >
<input type= "Submit" value= "Upload file" ><span id= "MSG" ></span>
<br>
<font color= "Red" > Support Jpg,jpeg,gif,bmp,swf,rmvb,rm,avi File Upload </font>
<iframe name= ' hidden_frame ' id= "hidden_frame" style= ' Display:none ' ></iframe>
</form>

</body>

<script type= "Text/javascript" >
function Callback (MSG)
{
document.getElementById ("file"). outerHTML = document.getElementById ("file"). outerHTML;
document.getElementById ("msg"). InnerHTML = "<font color=red>" +msg+ "</font>";
}
</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 files are 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 get the file from the foreground.
try {
FileList = upload.parserequest (request);
} catch (Fileuploadexception ex) {
Ex.printstacktrace ();
Return
}
The file name after saving
String imageName = null;
Easy access to the list of files from the front desk
Iterator<fileitem> it = Filelist.iterator ();
while (It.hasnext ()) {
Fileitem item = It.next ();
If it is not a normal form field, treat it 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 upload file closed", e);
}
}
if (out! = null) {
try {
Out.close ();
} catch (IOException e) {
Log.error ("Upload file off output failed", e);
}
}
}
}
}
PrintWriter out = null;
try {
out = Encodehead (request, response);
} catch (IOException e) {
E.printstacktrace ();
}
This place can not be less, otherwise the reception can not get the result of uploading

Out.write ("<script>parent.callback (' Upload file Success ') </script>);
Out.write (ImageName);
Out.close ();
}

/**
* Ajax helper method to get 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 ();
}
}

Ajax jsp no refresh upload file

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.