分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 软件开发

struts2之单文件上传(7)

发布时间:2023-09-06 01:23责任编辑:郭大石关键词:文件上传

前台页面jsp

<form action="uploadAction" enctype="multipart/form-data" method="post">
???<label>上传文件:</label>
???<input ?type="file" name="myfile"/>
???<input type="submit" value="提交"/>
???</form>

action

public class UploadAction extends ActionSupport {
//三个全局属性注意命名规则,属性名的前半部分保持一致,不然报空值
????//上传的文件(旧文件)
private File myfile;
//上传的文件名(旧文件)
private String myfileFileName;
//上传文件类型(旧文件)
private String myfileFileContentType;


//处理上传请求
public String upload(){
//生成新的文件名(使用uuid)
String newmyfilename = UUIDUtil.getUUID()+myfileFileName.substring(myfileFileName.lastIndexOf("."));
//指定上传的位置
String path = ServletActionContext.getServletContext().getRealPath("upload");
//上传文件的位置
String filepath = path+File.pathSeparator+newmyfilename;
System.out.println("filepath = "+filepath);
//构建新文件
File newfile = new File(filepath);

//读入写出 ????从旧文件读内容到新文件
FileInputStream fis = null;
FileOutputStream fos = null;

try {
//将旧文件封装到输入流
fis = new FileInputStream(myfile);
//将新文件封装到输出流
fos = new FileOutputStream(newfile);
//设置一个字节数组缓冲内容
byte [] bt = new byte[1024];
int len = 0;
/**
* 循环读取缓冲区的内容
* 输入流不断的将字节读入到缓冲区(旧文件到缓冲区)
* 输出流不断的将字节写出到新文件(缓冲区到新文件)
*/
while((len = fis.read(bt))!=-1){
fos.write(bt, 0, len);
}
fos.close();
fis.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


return ?SUCCESS;
}


public File getMyfile() {
return myfile;
}


public void setMyfile(File myfile) {
this.myfile = myfile;
}

public String getMyfileFileContentType() {
return myfileFileContentType;
}


public void setMyfileFileContentType(String myfileFileContentType) {
this.myfileFileContentType = myfileFileContentType;
}


public String getMyfileFileName() {
return myfileFileName;
}


public void setMyfileFileName(String myfileFileName) {
this.myfileFileName = myfileFileName;
}




}

struts.xml

<!-- struts2中文件上传拦截
???struts2 的核心包下的default.properties文件里有默认的大小为struts.multipart.maxSize=2097152,也就是2M. 这是struts2默认拦截,
?????????解决方法:在struts.xml配置文件中,添加
???????????<constant name="struts.multipart.maxSize" value="10485760"/>
??????????????????????????????这里的value单位为B,即10485760B = 10MB。
????-->
???<constant name="struts.multipart.maxSize" value="10485760"/>
???<package name="upload" namespace="/" extends="struts-default">
???????<action name="uploadAction" class="com.oak.action.UploadAction" method="upload">
????????????<result>
???????????????/welcome.jsp
????????????</result>
???????</action>
???</package>

struts2之单文件上传(7)

原文地址:http://www.cnblogs.com/love1/p/7808481.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved