The example of this article describes how to implement the file upload and download function in struts2 in java. Share it with everyone for your reference. The specific analysis is as follows:
1.File upload
The first is the code of the jsp page
Define an upload tag in the jsp page
Copy the code code as follows:<tr>
<td align="right" bgcolor="#F5F8F9"><b>Attachment:</b></td>
<td bgcolor="#FFFFFF">
<input type="file" name="upload" />
</td>
<td bgcolor="#FFFFFF"></td>
</tr>
Then the related attributes defined in BaseAction are omitted (you can also define them in your own Action, just change the access modifier)
Copy the code code as follows:/**
*Action base class
**/
public class BaseAction extends ActionSupport {
protected List<File> upload;
protected List<String> uploadContentType; //File type
protected List<String> uploadFileName; //File name
protected String savePath; //save path
}
Then there is an upload method in Action, the code is as follows:
Copy the code code as follows:/**
* 8. Upload attachments * @param upload
*/
public void uploadAccess(List<File> upload){
try {
if (null != upload) {
for (int i = 0; i < upload.size(); i++) {
String path = getSavePath() + ""+ getUploadFileName().get(i);
System.out.println(path);
item.setAccessory(getUploadFileName().get(i));
FileOutputStream fos = new FileOutputStream(path);
FileInputStream fis = new FileInputStream(getUpload().get(i));
byte[] buffer = new byte[1024];
int len = 0;
while ((len = fis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
fis.close();
fos.close();
}
}
} catch (Exception e) {
logger.error("Error uploading attachment.", e);
}
}
Then the copy code of my struts2.xml file is as follows: <action name="itemRDAction_*" method="{1}">
<param name="savePath">e:upload</param>
<interceptor-ref name="defaultStack">
<param name="fileUpload.allowedTypes">
application/octet-stream,image/pjpeg,image/bmp,image/jpg,image/png,image/gif,image/jpeg,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/vnd. ms-excel
</param>
<param name="fileUpload.maximumSize">8000000</param>
</interceptor-ref>
<result name="show_item_rd_upd"> /WEB-INF/jsp/page_item/updItem_rd.jsp</result>
<result name="show_item_rd_list"> /WEB-INF/jsp/page_item/listItem_rd.jsp</result>
<result name="show_item_rd_push"> /WEB-INF/jsp/page_item/pushItem_rd.jsp</result>
</action>
savePath is the save path, fileUpload.allowedTypes is used to limit the upload file type fileUpload.maximumSize file size limit
2.File download
First, copy the download link code on the page as follows: <tr>
<td align="right" bgcolor="#F5F8F9"><b>Attachment:</b></td>
<td bgcolor="#FFFFFF">
<div>${item.accessory}</div>
<c:if test="${!empty item.accessory}">
<div style="float: left;"><a style="color: black; text-decoration: none;" href="download.action?filename=${item.accessory}">Download</a>< /div>
</c:if>
</td>
<td bgcolor="#FFFFFF"></td>
</tr>
Next is the code for DownloadAction:
Copy the code code as follows:/**
* DownloadAction
*
* @author zhaoxz
*
*/
@Controller("downloadAction")
@Scope("prototype")
public class DownloadAction extends BaseAction {
/**
*
*/
private static final long serialVersionUID = -4278687717124480968L;
private static Logger logger = Logger.getLogger(DownloadAction.class);
private String filename;
private InputStream inputStream;
private String savePath;
private String mimeType;
public InputStream getInputStream() {
try {
String path = getSavePath() + "//"+ new String(filename.getBytes("ISO8859-1"), "utf-8");
System.out.println(path);
mimeType = ServletActionContext.getServletContext().getMimeType(path)+ ";charset=UTF-8";
inputStream = new FileInputStream(path);
String agent = request.getHeader("USER-AGENT");
System.out.println(agent);
if (null != agent) {
if (-1 != agent.indexOf("Firefox")) {// Firefox
mimeType = mimeType.replace("UTF-8", "ISO8859-1");
} else {// IE7+ Chrome
System.out.println("IE,Chrome");
filename = new String(filename.getBytes("ISO8859-1"),"utf-8");
filename = java.net.URLEncoder.encode(filename, "UTF-8");
}
}
} catch (Exception e) {
logger.error("Error downloading file information.", e);
}
if (null == inputStream) {
System.out.println("getResource error");
}
return inputStream;
}
public void setInputStream(InputStream inputStream) {
this.inputStream = inputStream;
}
@Override
public String execute() throws Exception {
return SUCCESS;
}
/****************************** get set ************************ **********/
public String getSavePath() {
return this.savePath;
}
public void setSavePath(String savePath) {
this.savePath = savePath;
}
public String getFilename() {
return filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
}
Then there is its struts2.xml file:
Copy the code as follows: <action name="download">
<param name="savePath">E:/upload</param>
<result type="stream">
<param name="contentType">${mimeType}</param>
<param name="contentDisposition">attachment;filename="${filename}"</param>
<param name="inputName">inputStream</param>
</result>
</action>
When downloading, pay attention to the encoding format and there should be no problem.
Problems encountered during uploading
1. Error occurs when uploading large files. Solution 1
The errors that occur are as follows:
1. 2012-02-24 11:06:31,937 ERROR (org.apache.struts2.dispatcher.Dispatcher:512) - Could not find action or result
No result defined for action com.iman.portal.action.QuestionActionImpl and result problemPage - action - file:/E:/myeclipse/workspaces/portal/WebRoot/WEB-INF/classes/struts2/struts-question.xml:51: 55
2. the request was rejected because its size (2973652) exceeds the configured maximum (2097152)
Chinese meaning: The request was rejected because its size (2973652) exceeds the configured maximum (2097152),
Considering the user experience, it is necessary to intercept such exceptions when uploading attachments. The solution is as follows:
1. The uploaded files are first stored in the cache during the upload process. For safety reasons, add a temporary storage path to the struts.properties file of the project, although the physical path of the server has been set in the project. .
Copy the code as follows: struts.multipart.saveDir=/temp
2. Considering that the size of the file upload may be modified later, regardless of whether it is the default or not, add the following configuration to the struts.properties file of the project:
Copy the code as follows: <!-- The allowed upload file size is 2M -->
<constant name="struts.multipart.maxSize" value="2097152"/>
3. struts.xml configuration
Copy the code as follows: <!-- How to modify the problem -->
<action name="updateProblem" method="updateProblem">
<interceptor-ref name="fileUpload"/>
<interceptor-ref name="defaultStack" />
<result name="input">/page/question/page/problemPage.jsp</result>
</action>
4. The most important and critical step
The fileUpload interceptor only determines the file type and size after the file is uploaded to the server. If we do nothing in Action, the exception will be displayed in front of the user, so I thought of a way to set the exception information as an Action-level error message. That is, override the addActionError method.
Copy the code code as follows: @Override
public void addActionError(String anErrorMessage) {
// Here we need to first determine whether it is an error we want to replace before processing it.
if (anErrorMessage.startsWith("the request was rejected because its size")) {
Pattern pattern = Pattern.compile("d+");
Matcher m = pattern.matcher(anErrorMessage);
// Match once
m.find();
String s1 =m.group();//Uploaded file size
// Match again
m.find();
String s2 =m.group();//limited size
if(!s1.equals("") && !s2.equals("")){
fileUploadErrorMessage="The size of the file you uploaded (" + Long.valueOf(s1)/1024 + "bytes) exceeds the allowed size (" + Long.valueOf(s2)/1024/1024 + "M)";
getRequest().setAttribute("fileUploadErrorMessage","The file is too large and exceeds the allowed size ("+Long.valueOf(s2)/1024/1024+"M). The upload failed!");
// Replace the information
super.addActionError(fileUploadErrorMessage);
}
} else {// Otherwise, handle it according to the original method
super.addActionError(anErrorMessage);
}
}
Yes, use <s:fielderror/> <s:fielderror/> on the return page to get the error content in addActionError.
Because I don't want to display the cause of the error on the page and want to pop up a prompt box, I put the information into the request object.
When the page is loaded, the following js verification is added:
Copy the code code as follows: // Determine whether the file is uploaded successfully
var message="${request.fileUploadErrorMessage}";
if(message!=null && ""!=trim(message) && message!="null"){
self.parent.diag.close();
alert(message);
return;
}
Here are some references to understand Dongdong:
struts.multipart.maxSize controls the maximum size of files uploaded by the entire project
The maximumSize attributes of struts.multipart.maxSize and fileUpload interceptors have different divisions of labor, which are summarized as follows:
1.struts.multipart.maxSize controls the maximum size of the uploaded files in the entire project.
If this size is exceeded, an error will be reported in the background and the program cannot handle such a large file. There will be the following prompt in fielderror:
the request was rejected because its size (16272982) exceeds the configured maximum (9000000)
2. The maximumSize attribute of the fileUpload interceptor must be less than the value of struts.multipart.maxSize.
The default struts.multipart.maxSize is 2M. When maximumSize is greater than 2M, the value of struts.multipart.maxSize must be set greater than maximumSize.
3. When the uploaded file is larger than struts.multipart.maxSize, the system reports an error. When the uploaded file is between struts.multipart.maxSize and maximumSize, the system prompts:
File too large: file "MSF concept.ppt" "upload__5133e516_129ce85285f__7ffa_00000005.tmp" 6007104
When the uploaded file is smaller than maximumSize, the upload is successful.
Copy the code as follows: <action name="UploadFile">
<result name="UploadFileResult">/pages/ShowOtherFiles.jsp</result>
<result name="JGBsuccess">/pages/JGBdetail.jsp</result>
<interceptor-ref name="fileUpload">
<param name="savePath">/data</param>
<param name="maximumSize">52428800</param>
</interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref>
</action>
An error occurs when uploading large files. Solution 2:
Problem: Error when uploading large files...
Solution: Modify the parameters in the struts.xml file as follows. Copy the code as follows: <constant name="struts.multipart.maxSize" value="55000000"/>
<action name="UploadFile">
<result name="UploadFileResult">/www.VeVB.COm/ ShowOtherFiles.jsp</result>
<result name="JGBsuccess">/pages/JGBdetail.jsp</result>
<interceptor-ref name="fileUpload">
<param name="savePath">/data</param>
<param name="maximumSize">52428800</param>
</interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref>
</action>
The relationship between the size in the struts.xml file and the actual file size: 1048576 (Bytes) = 1024*1024 = 1M actual file size.
struts.multipart.maxSize controls the maximum size of files uploaded by the entire project
The maximumSize attributes of struts.multipart.maxSize and fileUpload interceptors have different divisions of labor, which are summarized as follows:
1.struts.multipart.maxSize controls the maximum size of the uploaded files in the entire project. If this size is exceeded, an error will be reported in the background and the program cannot handle such a large file. There will be the following prompt in fielderror:
the request was rejected because its size (16272982) exceeds the configured maximum (9000000)
2. The maximumSize attribute of the fileUpload interceptor must be less than the value of struts.multipart.maxSize.
The default struts.multipart.maxSize is 2M. When maximumSize is greater than 2M, the value of struts.multipart.maxSize must be set greater than maximumSize.
3. When the uploaded file is larger than struts.multipart.maxSize, the system reports an error. When the uploaded file is between struts.multipart.maxSize and maximumSize, the system prompts:
File too large: file "MSF concept.ppt" "upload__5133e516_129ce85285f__7ffa_00000005.tmp" 6007104
When the uploaded file is smaller than maximumSize, the upload is successful.
Upload file type restrictions
Configure fileupload interceptor
The defaultStack of struts2 already contains the fileupload interceptor. If you want to add the allowedTypes parameter, you need to write a new defaultstack, copy it and modify it:
Copy the code as follows: <interceptors>
<interceptor-stack name="myDefaultStack">
<interceptor-ref name="exception"/>
<interceptor-ref name="alias"/>
<interceptor-ref name="servletConfig"/>
<interceptor-ref name="i18n"/>
<interceptor-ref name=www.VeVB.COm/>
<interceptor-ref name="chain"/>
<interceptor-ref name="debugging"/>
<interceptor-ref name="profiling"/>
<interceptor-ref name="scopedModelDriven"/>
<interceptor-ref name="modelDriven"/>
<interceptor-ref name="fileUpload">
<param name="allowedTypes">
image/png,image/gif,image/jpeg
</param>
</interceptor-ref>
<interceptor-ref name="checkbox"/>
<interceptor-ref name="staticParams"/>
<interceptor-ref name="actionMappingParams"/>
<interceptor-ref name="params">
<param name="excludeParams">dojo..*,^struts..*</param>
</interceptor-ref>
<interceptor-ref name="conversionError"/>
<interceptor-ref name="validation">
<param name="excludeMethods">input,back,cancel,browse</param>
</interceptor-ref>
<interceptor-ref name="workflow">
<param name="excludeMethods">input,back,cancel,browse</param>
</interceptor-ref>
</interceptor-stack>
</interceptors>
<default-interceptor-ref name="myDefaultStack"></default-interceptor-ref>
Only modify the copied code in the code as follows: <interceptor-ref name="fileUpload">
<param name="allowedTypes">
image/png,image/gif,image/jpeg
</param>
</interceptor-ref>
The interceptor stack is configured inside the <package> tag and outside the <action> tag as above. If we define it as the default interceptor, we don’t need to
Introduce it in the <action> tag. If not, you need to introduce an interceptor. Copy the code. The code is as follows: <action>
<result name="input">/error/dbError.jsp</result>
<interceptor-ref name="myDefaultStack"></interceptor-ref>
</action>
File upload type error action will directly return input, so there is no need to return "input" in the action;
You can also define the path and size of your upload request outside the <package> tag:
Copy the code as follows: <constant name="struts.multipart.saveDir" value="/upload/detailed"></constant>
<constant name="struts.multipart.maxSize" value="1024"></constant>
The most important point: the form for uploading files must add: enctype="multipart/form-data". If not, an input error will be reported.
I hope this article will be helpful to everyone’s Java programming.