struts2文件下载

如果想知道struts2文件上传与打开可以登录以下地址:https://blog.youkuaiyun.com/qq_42694534/article/details/84204650

这是前端代码

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title> 
</head>
<body> 
<a href="${pageContext.request.contextPath }/sy/fileAction_saveAs.action">下载</a>
</body>
</html>

后端的action代码如下:
注意:这里需要到commons-io-2.5.jar,commons-fileupload-1.3.3.jar(文件上传与下载所使用的包)

package com.zking.five;

import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.apache.coyote.http11.filters.BufferedInputFilter;

import com.zking.test.web.BaseAction; 
public class fileAction extends BaseAction {
	// 这是jsp传递过来的具体文件
	private File file;
	// 文件名
	private String fileFileName;
	// 文件类型
	private String fileContentType;
	// 虚拟路径,upload是要保存的文件夹
	private String serverDir = "/upload"; 
 /**
	 * 下载图片
	 * 
	 * @return
	 * @throws IOException 
	 */
	public voidsaveAs() throws IOException {
		// 从数据库获取fileName,fileType
		String fileName = "s1.jpg";//图片的名字
		String fileType = "image/jpg";
		response.setContentType(fileType);
		response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
		String realPath = getRealPath(serverDir + "/" + fileName);
		// 从服务器获取图片写到本地
		FileUtils.copyFile(new File(realPath), response.getOutputStream()); 
	}
	
	/**
	 * 获取文件夹的真实路径
	 * 
	 * @param path
	 * @return
	 */
	private String getRealPath(String path) {
		return this.request.getServletContext().getRealPath(path);
	}

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

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值