Click here to download the project code
Due to project requirements, asynchronous file upload is required when processing file uploads. Here we use Jquery Ajax File Uploader this component: http://www.phpletter.com/download_project_version.php? Version_id = 6
The server uses struts2 to process file uploads.
Required environment:
Jquery. js
Ajaxfileupload. js
Jar package on which struts2 depends
And struts2-json-plugin-2.1.8.1.jar
Compile the Action for File Upload
Copy codeThe Code is as follows: package com. ajaxfile. action;
Import java. io. File;
Import java. io. FileInputStream;
Import java. io. FileOutputStream;
Import org. apache. struts2.ServletActionContext;
Import com. opensymphony. xwork2.ActionSupport;
@ SuppressWarnings ("serial ")
Public class FileAction extends ActionSupport {
Private File file;
Private String fileFileName;
Private String fileFileContentType;
Private String message = "you have successfully uploaded the file ";
Public String getMessage (){
Return message;
}
Public void setMessage (String message ){
This. message = message;
}
Public File getFile (){
Return file;
}
Public void setFile (File file ){
This. file = file;
}
Public String getFileFileName (){
Return fileFileName;
}
Public void setFileFileName (String fileFileName ){
This. fileFileName = fileFileName;
}
Public String getFileFileContentType (){
Return fileFileContentType;
}
Public void setFileFileContentType (String fileFileContentType ){
This. fileFileContentType = fileFileContentType;
}
@ SuppressWarnings ("deprecation ")
@ Override
Public String execute () throws Exception {
String path = ServletActionContext. getRequest (). getRealPath ("/upload ");
Try {
File f = this. getFile ();
If (this. getFileFileName (). endsWith (". exe ")){
Message = "sorry, the format of the file you uploaded is not allowed !!! ";
Return ERROR;
}
FileInputStream inputStream = new FileInputStream (f );
FileOutputStream outputStream = new FileOutputStream (path + "/" + this. getFileFileName ());
Byte [] buf = new byte [1, 1024];
Int length = 0;
While (length = inputStream. read (buf ))! =-1 ){
OutputStream. write (buf, 0, length );
}
InputStream. close ();
OutputStream. flush ();
} Catch (Exception e ){
E. printStackTrace ();
Message = "sorry, File Upload Failed !!!! ";
}
Return SUCCESS;
}
}
Struts. xmlCopy codeThe Code is as follows: <? Xml version = "1.0" encoding = "UTF-8"?>
<! DOCTYPE struts PUBLIC "-// Apache Software Foundation // DTD Struts Configuration 2.1 // EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<Struts>
<Package name = "struts2" extends = "json-default">
<Action name = "fileUploadAction" class = "com. ajaxfile. action. FileAction">
<Result type = "json" name = "success">
<Param name = "contentType">
Text/html
</Param>
</Result>
<Result type = "json" name = "error">
<Param name = "contentType">
Text/html
</Param>
</Result>
</Action>
</Package>
</Struts>
Observe the result configuration in struts. xml in combination with Action.
The contentType parameter is required. Otherwise, the browser always prompts to save the returned JSON result as a file and will not submit it to ajaxfileupload for processing. This is because the default contentType of struts2 JSON Plugin is application/json, while the ajaxfileupload requires text/html.
Jsp page for File UploadCopy codeThe Code is as follows: <% @ page language = "java" contentType = "text/html; charset = UTF-8"
PageEncoding = "UTF-8" %>
<! DOCTYPE html PUBLIC "-// W3C // dtd html 4.01 Transitional // EN" "http://www.w3.org/TR/html4/loose.dtd">
<Html>
<Head>
<Meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8">
<Title> Insert title here </title>
<Script type = "text/javascript" src = "js/jquery. js"> </script>
<Script type = "text/javascript" src = "js/ajaxfileupload. js"> </script>
<Script type = "text/javascript">
Function ajaxFileUpload ()
{
$ ("# Loading ")
. AjaxStart (function (){
$ (This). show ();
}) // A picture is displayed when a file is uploaded.
. AjaxComplete (function (){
$ (This). hide ();
}); // Hide the image after the file is uploaded
$. AjaxFileUpload
(
{
Url: 'fileuploadaction. action', // server-side request address used for File Upload
Secureuri: false, // this parameter is generally set to false.
FileElementId: 'file', // id attribute of the file upload space <input type = "file" id = "file" name = "file"/>
DataType: 'json', // the return value type is generally set to json
Success: function (data, status) // the server responds to the processing function successfully.
{
Alert (data. message); // extract the data in the message from the json returned by the server. The message is the member variable defined in the action in struts2.
If (typeof (data. error )! = 'Undefined ')
{
If (data. error! = '')
{
Alert (data. error );
} Else
{
Alert (data. message );
}
}
},
Error: function (data, status, e) // server response failure processing function
{
Alert (e );
}
}
)
Return false;
}
</Script>
</Head>
<Body>
<Input type = "file" id = "file" name = "file"/>
<Br/>
<Input type = "button" value = "Upload" onclick = "return ajaxFileUpload ();">
</Body>
</Html>
Observe the code in <body> and there is no form. Only the ajaxFileUpload () method is triggered when the button is clicked. Note the order in which JavaScript files are introduced. ajaxfileupload. js depends on jquery, so you know.
Click here to download the project code