下面的代码是上传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() + "//" + uploadFileName); if (newExcel.exists()) { newExcel.delete(); } try { FileUtils.copyFile(upload, newExcel); } catch (Exception e) { e.printStackTrace(); } // 删除临时文件 upload.delete(); return "uploadExcelSuccess"; }
}
新闻热点
疑难解答