Struts2 实现文件上传下载 (下载支持中文文件名)代码
2018-07-20 来源:open-open
struts2 实现文件上传:
Action 代码:
package com.action;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class FileUploadAction extends BaseAction{
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* 上传后存放在临时文件夹里的文件
*/
private File <span style="color:#ff0000;">file;</span>
/**
* 文件名称
*/
private String <span style="color:#ff0000;">fileFileName</span>;
/**
* 文件的MIME类型
*/
private String<span style="color:#ff0000;"> fileContentType</span>;
/**
* 保存的路径
*/
private String savePath;
public String getSavePath() {
return savePath;
}
public void setSavePath(String savePath) {
this.savePath = savePath;
}
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
public String getFileFileName() {
return fileFileName;
}
public void setFileFileName(String fileFileName) {
this.fileFileName = fileFileName;
}
public String getFileContentType() {
return fileContentType;
}
public void setFileContentType(String fileContentType) {
this.fileContentType = fileContentType;
}
public String execute() throws Exception
{
String root = ServletActionContext.getServletContext().getRealPath(savePath);
InputStream is = new FileInputStream(file);
OutputStream os = new FileOutputStream(new File(root, fileFileName));
byte[] buffer = new byte[500];
@SuppressWarnings("unused")
int length = 0;
while(-1 != (length = is.read(buffer, 0, buffer.length)))
{
os.write(buffer);
}
os.close();
is.close();
return SUCCESS;
}
}
struts2.xml配置信息:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="fileUpload" extends="struts-default" namespace="/">
<action name="fileUpload_*" class="com.action.FileUploadAction" method="{1}">
<param name="savePath">/upload</param> //注意在当前工程里建一个 upload文件夹
<result>
/login.jsp
</result>
</action>
</package>
</struts>
文件上传的 jsp 页面:
<form action="fileUpload.action" method="post" enctype="multipart/form-data">
file: <input type="file" name="file"/><br>
<input type="submit" value="submit"/>
</form>
struts2实现文件下载源码:支持中文文件名
注意:下载文件的大小设置问题,默认是2M. 可以在struts.properties 设置 struts.multipart.maxSize=10485760 (10M 大小根据自己情况)
标签: 代码
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点!
本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。
上一篇:使用python进行密码暴力破解
下一篇:Python实现文件的压缩及解压
最新资讯
热门推荐