【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;
		}
		
	

猜你喜欢

转载自blog.csdn.net/qq_40979551/article/details/83119472
今日推荐