使用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";
}