JAVAWeb SSH框架 上传文件,如2007的EXCEL
下面的代码是上传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";
}
}
最新文章
- 禁止chrome记住密码
- Conversion Operators in OpenCascade
- Spring学习笔记之四----基于Annotation的Spring AOP编程
- Git命令行(转用于学习和记录)
- ZT 螨虫知识2
- iOS进阶_地图上定位的标志——大头针
- Windows去除快捷箭头
- ThinkPHP5.0完全开发手册
- 不使用配置文件动态注册HttpModule
- jquery 实现页面局部刷新ajax做法
- 制作PHP安装程序的原理和步骤56
- mysql HA方案: MHA
- 相关Jquery Validator采用
- NOIP2010-普及组复赛-第四题-三国游戏
- ECOS-认证地址
- 29.使用register_chrdev_region()系列来注册字符设备
- tinyxml的封装与使用(转载)
- 如何修改WinPE Boot的.wim镜像文件
- 百川sdk----自己的WebViewClient不被执行【废弃,新版本百川已修复此问题】
- Spring Boot Logback日志配置
热门文章
- 【Mybatis】Insert批量操作
- 3.25课&#183;&#183;&#183;&#183;&#183;&#183;&#183;&#183;&#183;JavaScript简介与语法
- LintCode:链表操作(合并与反转)
- python3 函数 二
- P4773 红鲤鱼与绿鲤鱼
- dedecms常用标签
- MySQL存储过程入门教程
- EntityFramework 学习 一 Spatial Data type support in Entity Framework 5.0
- LINQ 学习路程 -- 查询操作 Distinct Except Intersect Union
- 算法(Algorithms)第4版 练习 1.5.14