下面的代碼是上傳EXCEL的代碼,其實,就是在上傳文件到服務器,代碼都差不多,只是接收的文件的類型改一下即可。
1.jsp 用的是struts2 標簽
代碼:
<s:file name="upload">
用form表單提交到Action
2.struts2 代碼:
<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> //允許上傳的文件類型,這個是2007EXCEL,即XLSX后綴 </action>
3.Action代碼:
public class UploadExcelAction extends ActionSupport {
private File upload;(get,set代碼省略,自動生成的代碼而已)//用于接住jsp傳過來的EXCEL文件 private String uploadFileName;(get,set代碼省略 ,自動生成的代碼而已)//這個值不用進行處理,就能得到你傳過來的EXCEL的文件名
//uploadContentType這個值不用進行處理,就能得到你傳過來的EXCEL文件的類型
//如: 如果是2007的EXCEL,就是application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
private String uploadContentType;(get,set代碼省略,自動生成的代碼而已)
private String allowedTypes;(get,set代碼省略,自動生成的代碼而已)//接住在struts2設置的值,用于進行文件類型驗證
private String savePath; //設置絕對路徑,用于存放上傳的EXCEL,get方法代碼修改了,set 方法不變如下:
public String getSavePath() { return savePath = ServletActionContext.getServletContext().getRealPath( "/uploadExcel"); } public void setSavePath(String savePath) { this.savePath = savePath; }
public String uploadExcel() throws Exception { // 驗證文件格式 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() + "http://" + uploadFileName); if (newExcel.exists()) { newExcel.delete(); } try { FileUtils.copyFile(upload, newExcel); } catch (Exception e) { e.printStackTrace(); } // 刪除臨時文件 upload.delete(); return "uploadExcelSuccess"; }
}
新聞熱點
疑難解答