Struts2通过指定地址文件名称下载文件。

使用Struts2框架,解决通过http请求文件跨域,下载文件到本地。记录简单代码实现,
在Struts.xml文件写入一下代码:

<!-- 下载图片 -->
		<action name="download" class="com.blue.core.code.itineraryInfo.web.ItineraryInfoAction" method="download">
			<result type="stream">
                <!-- 以什么形式下载 默认为在线下载   并指定文件名 -->
                <param name="contentDisposition">attachment;filename=${fileName}</param>
                <!-- Action里的流的名称 -->
                <param name="inputName">inputStream</param>
            </result>
		</action>

在Controller层中只要写入重要的两行代码即可:

private InputStream inputStream;
private String fileName;//文件名随意
    public InputStream getInputStream() {
        return inputStream;
    }
    public void setInputStream(InputStream inputStream) {
        this.inputStream = inputStream;
    }
    public String getFileName() {
        return fileName;
    }
    public void setFileName(String fileName) {
        this.fileName = fileName;
    }
	@RequestMapping("/download")
    public String download() throws IOException{
		fileName =this.getRequest().getParameter("imageName");
		//其中/images/trip/是代表项目中的存储文件夹。所需要下载的图片文件一定是在这个文件夹中。
        inputStream = ServletActionContext.getServletContext().getResourceAsStream("/images/trip/"+fileName);
    	return "success";
    }

以下是直接通过http文件地址请求下载:

@RequestMapping("/download")
    public String download() throws IOException{
		String imgUrl =this.getRequest().getParameter("imageUrl");
		// 统一资源
        URL url = new URL(imgUrl);
        // 连接类的父类,抽象类
        URLConnection urlConnection = url.openConnection();
        // http的连接类
        HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
        // 设定请求的方法,默认是GET
        httpURLConnection.setRequestMethod("POST");
        // 设置字符编码
        httpURLConnection.setRequestProperty("Charset", "UTF-8");
        // 打开到此 URL 引用的资源的通信链接(如果尚未建立这样的连接)。
        httpURLConnection.connect();
        inputStream = httpURLConnection.getInputStream();
//        inputStream = ServletActionContext.getServletContext().getResourceAsStream("/images/trip/"+fileName);
        fileName = imgUrl.substring(imgUrl.lastIndexOf("/")+1, imgUrl.length());
    	return "success";
    }
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值