因为业务的需要,公司产品要求商品详情页面有个下载的功能
找了很多的方法,发现有的需要打开一个新窗口,而且在某些浏览器上不适用,所以继续寻找更好的方法
跟同事沟通后发现他那里有个下载的方法,不过是C#写的,改了改发现有些地方不太通用,所以继续百度。
后来找到一段可以用的代码,用了自己的前端js代码,加上百度的java代码修改后,发现可以达到自己的需求
于是,更新博客,留作以后使用。
本套代码示例基于springMVC 开发;
Java代码如下:
1.首先编写cotroller进行调用;
@RequestMapping(value="downLoadFromUrl")
public void downLoadFromUrl(HttpServletRequest request,HttpServletResponse response) throws IOException{
DownloadUtils.downLoadFromUrl(request, response);
}
2.下载功能的实现代码DownloadUtils;
package com.utils; import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; /**
* 在线下载图片功能*/
public class DownloadUtils {
public static void downLoadFromUrl(HttpServletRequest request,HttpServletResponse response) throws IOException{
String downloadUrl = request.getParameter("fileName");
URL url = new URL(downloadUrl);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
//设置超时间为3秒
conn.setConnectTimeout(3*1000);
//防止屏蔽程序抓取而返回403错误
conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
//得到输入流
InputStream inputStream = conn.getInputStream();
try {
String[] fileNameParts = downloadUrl.split("/");
String fileName = fileNameParts[fileNameParts.length - 1];
// String fileName = "aaa.jpg";
fileName = new String(fileName.getBytes("UTF-8"),"ISO8859-1");
response.setContentType("application/octet-stream");
response.addHeader("Content-Disposition", "attachment;filename="+fileName);
String len = String.valueOf(inputStream.available()/1000+"k");
response.setHeader("Content-Length", len);
OutputStream out = response.getOutputStream();
byte[] getData = readInputStream(inputStream);
out.write(getData);
inputStream.close();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} /**
* 从输入流中获取字节数组
* @param inputStream
* @return
* @throws IOException
*/
public static byte[] readInputStream(InputStream inputStream) throws IOException {
byte[] buffer = new byte[1024];
int len = 0;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
while((len = inputStream.read(buffer)) != -1) {
bos.write(buffer, 0, len);
}
bos.close();
return bos.toByteArray();
}
}
3.js代码如下;
function downloadFile() {
var pic=$("input[name='pic']
window.location = "/product_big/downLoadFromUrl?fileName="+pic;
}
最后感谢万能的百度
下面这个是打包下载文件的java代码,上面的是直接下载图片的,下面这个可以实现批量打包下载
@RequestMapping(value = "/downLoadImage", method = RequestMethod.GET)
public void downLoadImage(HttpServletRequest request, HttpServletResponse response) throws Exception {
List<String> urls = Lists.newArrayList();
String path = request.getParameter("pictureUrl");
urls.add(path);
Map<String, InputStream> isMap = Maps.newHashMap();
for (String urlStr : urls) {
String[] fileNameParts = urlStr.split("/");
String fileName = fileNameParts[fileNameParts.length - 1];
try {
URL url = new URL(urlStr);
URLConnection con = url.openConnection();
// 设置超时间为3秒
con.setConnectTimeout(3 * 1000);
// 防止屏蔽程序抓取而返回403错误
con.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
InputStream is = con.getInputStream();
isMap.put(fileName, is);
} catch (Exception e) {
e.printStackTrace();
}
}
String[] fileNameParts = path.split("/");
String fileNames = fileNameParts[fileNameParts.length - 1];
response.setContentType("application/octet-stream");
String filename = URLEncoder.encode(fileNames, "UTF-8");
response.setHeader("Content-Disposition", "attachment; filename=" + filename + ".zip");
ZipOutputStream zipOut = new ZipOutputStream(response.getOutputStream());
for (Entry<String, InputStream> is : isMap.entrySet()) {
String fileName = is.getKey();
InputStream value = is.getValue();
try {
addToZip(value, zipOut, fileName); } catch (Exception e) {
e.printStackTrace();
}
}
zipOut.flush();
zipOut.close(); } private void addToZip(InputStream is,ZipOutputStream zipOut, String fileName) throws IOException {
fileName = URLEncoder.encode(fileName, "UTF-8");
ZipEntry entry = new ZipEntry(fileName);
zipOut.putNextEntry(entry);
int len;
byte[] buffer = new byte[1024];
while ((len = is.read(buffer)) > 0) { zipOut.write(buffer, 0, len);
}
zipOut.closeEntry();
is.close();
}