The following code is the code to upload Excel, in fact, is to upload files to the server, the code is similar, just the type of the received files can be changed.
1.jsp is a struts2 tag.
Code:
<s:file name= "Upload" >
Submit to action with form form
2.STRUTS2 Code:
<action name= "Uploadexcel" class= "Com.javaweb.action.UploadExcelAction"
method= "Uploadexcel" >
<result name= "Uploadexcelsuccess" >
view/uploadexcelsuccess.jsp
</result>
<result name= "Error" >
view/uploadexcelerr.jsp
</result>
<param name= "Allowedtypes" >application/vnd.openxmlformats-officedocument.spreadsheetml.sheet</param >//Allow upload of file types, this is the 2007EXCEL, which is the xlsx suffix
</action>
3.Action Code:
public class Uploadexcelaction extends Actionsupport {
Private File upload; (get,set code omitted, automatically generated code only)//used to catch the JSP sent over the Excel file
Private String uploadfilename; (get,set code omitted, automatically generated code only)//This value does not have to be processed, you can get the file name of Excel that you passed.
Uploadcontenttype This value is not processed, you can get the type of Excel file you passed.
such as: If it is 2007 Excel, it is Application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
Private String Uploadcontenttype; (get,set code omitted, auto-generated code only)
Private String allowedtypes; (get,set code omitted, automatically generated code only)//catch the value set in struts2 for file type validation
Private String Savepath; To set the absolute path, the Excel,get method code for the upload is modified, and the Set method is unchanged as follows:
Public String Getsavepath () {
return Savepath = Servletactioncontext.getservletcontext (). Getrealpath (
"/uploadexcel");
}
public void Setsavepath (String savepath) {
This.savepath = Savepath;
}
Public String Uploadexcel () throws Exception {
Verifying file formats
Boolean flag = false;
string[] Allowedtypesstr = Allowedtypes.split (",");
for (int i = 0; i < allowedtypesstr.length; i++) {
if (Uploadcontenttype.equals (Allowedtypesstr[i])) {
Flag = true;
}
}
if (flag = = False) {
return "error";
}
File Newexcel = new file (Getsavepath () + "\ \" + uploadfilename);
if (newexcel.exists ()) {
Newexcel.delete ();
}
try {
Fileutils.copyfile (upload, newexcel);
} catch (Exception e) {
E.printstacktrace ();
}
Delete temporary files
Upload.delete ();
return "Uploadexcelsuccess";
}
}
Javaweb SSH framework to upload files, such as 2007 of Excel