Struts2之文件上传与下载

1、文件上传三种方式:

将文件以二进制的形式保存到数据库中 activiti工作流框架
将文件存储到专门文件服务器(存放文件用的Linux系统)中
直接将文件存储到服务器(tomcat所在服务器)中
2、文件上传的一个实例:

action里的代码如下

public class UploadAction extends BaseAction implements ModelDriven<Student>{
	private File file;// xxx
	private String fileContentType;// xxxContentType
	private String fileFileName;// xxxFileName

	 private StudentDAO studentDao=new StudentDAO();
	 private Student student=new Student();
	private String serverDir = "/upload";
    
	
	public String upload() {
		System.out.println(file);
		System.out.println(fileContentType);
		System.out.println(fileFileName);
		System.out.println("============================");
		String realPath = getRealPath(serverDir + "/" + fileFileName);
		System.out.println(realPath);
//		参数1:本地文件
//		参数2:tomcat服务器文件
		
		try {
			FileUtils.copyFile(file, new File(realPath));
		} catch (IOException e) {
			e.printStackTrace();
		}
		return SUCCESS;
	}
	/**
	 * 获取Linux目录的真实路径
	 * @param string	指的是本地路径(相对于工程WebContent所在的路径)
	 */
	private String getRealPath(String path) {
		return appliaction.getRealPath(path);
	}

jsp页面的代码如下:

<form action="${pageContext.request.contextPath }/sy/uploadAction_upload.action" enctype="multipart/form-data" method="post">
	<input type="file" name="file">
	<input type="submit" value="上传">
</form>

3、文件下载的一个实例:

action里的代码如下:

public String openAs() {
		String type = "image/jpeg";
		String name = "IMG_0933.JPG";
		response.setContentType(type);
		response.setHeader("Content-Disposition","filename=" + name);//文件名
		/*
		 * 从服务器拿图片到本地
		 * 	源:服务器
		 * 	目的:jsp输出图片
		 */
		File serverFile = new File(getRealPath(serverDir + "/" + name));
		try {
			FileUtils.copyFile(serverFile, response.getOutputStream());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

jsp页面的代码如下:

<h2>直接展示</h2>
<s:url var="openAsUrl" namespace="/sy" action="uploadAction_openAs"></s:url>
---
<img alt="" src='<s:property value="#openAsUrl"/>'>

处理文件名的中文乱码:
String fileName = d.getFileName();
fileName = new String(fileName.getBytes(“utf-8”), “iso8859-1”);

struts2文件上传大小设置:

struts2文件上传类型设置(通过配置拦截器):
根据struts2自带的fileupload拦截器中提供的allowedTypes来进行限制

image/png,image/gif,image/jpeg

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值