Jsp version ajax File Upload
Jsp uses ajax + jquery to upload images without refreshing
The first step to import the needed package, jquery. js, ajaxfileupload. js, to the http://www.phpletter.com to download ajaxfileupload package
The HTML code is as follows:
<! Doctype html public "-// W3C // dtd html 4.01 Transitional // EN">
<Html>
<Head>
<Title> Ajax does not need to upload any new files </title>
<! -- Introduce relevant js files and relative paths -->
<Script type = "text/javascript" src = "js/jquery. js"> </script>
<Script type = "text/javascript" src = "js/ajaxfileupload. js"> </script>
<Script type = "text/javascript">
Function ajaxFileUpload (){
$. AjaxFileUpload ({
Url: 'image. do? Stats = uploadimag', // link to the server address
Secureuri: false,
FileElementId: 'editorimg ', // id attribute of the file selection box
DataType: 'text', // format returned by the server, which can be json
Success: function (data, status) // equivalent to the usage of the try statement block in java
{
Alert (data); // data is returned from the server
('{Result'{.html ('image uploaded successfully ');
},
Error: function (data, status, e) // equivalent to the catch Block usage in java
{
Upload ('{result'{.html ('image upload failed ');
}
}
);
}
</Script>
</Head>
<Body>
<Form name = "padd" id = "padd" enctype = "multipart/form-data">
<Input type = "file" id = "editorImg" name = "editorImg"/>
<Input type = "button" onclick = "ajaxFileUpload ();" value = "Upload">
</Form>
<Div id = "result"> </div>
</Body>
</Html>
I used the Struts self-generated Upload Component in the background for uploading. The Struts configuration value is needless to say. The Code is as follows:
// Form class
Public class ProductForm extends ActionForm {
// This must be the same as the file id of the HTML page
Private FormFile editorImg;
Public FormFile getEditorImg (){
Return editorImg;
}
Public void setEditorImg (FormFile editorImg ){
This. editorImg = editorImg;
}
}
// Action class
Public class ProductAction extends DispatchAction {
Public ActionForward uploadImage (ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
Throws Exception {
Response. setContentType ("text/html; charset = GBK ");
// Obtain the path of the current project in Tomcat
String path = request. getSession (). getServletContext (). getRealPath ("images ");
ProductForm pf = (ProductForm) form;
FormFile file = pf. getEditorImg ();
FileOutputStream fos = new FileOutputStream (path + "/" + file. getFileName ());
// Write the file to the specified path
Fos. write (file. getFileData ());
Fos. flush ();
Fos. close ();
PrintWriter out = response. getWriter ();
Out. println (file. getFileName ());
Return null;
}
}