【struts】文件上传下载(直接打开)

 

文件上传

①:表单部分【必须设置二进制】(注意demo文件选择器的name为file

(demo是根据sid上传)

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

②:子控制器:

	private File file;//这里必须跟你文件选择器的name一致,不然会报错
	private String fileContentType;
	private String fileFileName;//(需提供get/set方法)
	
	private String serverDir = "/uplaod";//指定你要上传的文件夹
    
    
    //文件上传
	public String upload() {
		/**
		 * srcFile  参数1:指的是本地文件
		 * destFile 参数2:指的是在服务器生成的文件
		 */
		String realPath = getRealPath(serverDir + "/" +fileFileName);
		try {
			FileUtils.copyFile(file, new File(realPath));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return SUCCESS;
	}

    /**
	 * 获取Linux下的上传文件所在的位置   
	 * @param path
	 * @return
	 */
	private String getRealPath(String path) {
		// TODO Auto-generated method stub
		return application.getRealPath(path);
	}
	
    

直接打开与文件下载

①:jsp部分(demo的数据库文件分开为两列,一列存储文件,一列存储文件类型)

<!-- 直接打开 -->
<s:url var="openAsUrl" namespace="/sy" action="uploadAction_openAs.action">
					<s:param name="spicture" value="#s.spicture"></s:param>
					<s:param name="stype" value="#s.stype"></s:param>
			    </s:url>
<img alt="" src='<s:property value="openAsUrl"/>' width="60px" height="60px">
<!-- 文件下载 -->
<s:url var="downloadUrl" namespace="/sy" action="uploadAction_download.action">
    <s:param name="spicture" value="#s.spicture"></s:param>
    <s:param name="stype" value="#s.stype"></s:param>
</s:url>
<s:a href="%{#downloadUrl}">下载</s:a>

②:子控制器部分

//直接打开
public String openAs() {
		response.setContentType(student.getStype());
		response.setHeader("Content-Disposition","filename=" + student.getSpicture());
		String realPath = getRealPath(serverDir + "/" +student.getSpicture());
		try {
			FileUtils.copyFile(new File(realPath), response.getOutputStream());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	
//文件下载	
	public String download() {
			response.setContentType(student.getStype());
			response.setHeader("Content-Disposition","attachment;filename=" +             
            student.getSpicture());//文件名
			String realPath = getRealPath(serverDir + "/" +student.getSpicture());
			try {
				FileUtils.copyFile(new File(realPath), response.getOutputStream());
			} catch (IOException e) {
				e.printStackTrace();
			}
			return null;
		}
		
	

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值