1.java实现web图片下载
方法一:用 download 属性,就可以提供下载。但是只有 Firefox 和 Chrome 支持 download 属性。
举例:点击下载
这个简单的download属性就完成了下载。
方法二:通过url下载图片,比如:http:\127.0.0.1:8080\ecMarket\images\lunbo1.JPG
说明:是http这种url,就需要用URLConnection conn = url.openConnection();获取远程url的资源,
不然就会报 (文件名、目录名或卷标语法不正确。)错误,识别不了。
public void get() throws Exception {
HttpServletResponse response = getResponse();
//获得图片路径
String fileName = getRequest().getParameter("path");
URL url = new URL(fileName);
//获取远程url的资源
URLConnection conn = url.openConnection();
//截取图片名
String fName=fileName.substring(fileName.lastIndexOf("/")+1);
//拼接图片绝对路径 如果相片放在tomcat-bin目录下 通过下面代码可以获取bin目录,然后在加图片包名。
// String fileDir= System.getProperty("user.dir")+ File.separator+fname;
//设置Content-Disposition
response.setHeader("Content-Disposition", "attachment;filename="+toUtf8String(fName));
//读取图片,通过response将目标图片写到客户端
BufferedImage image = ImageIO.read(conn.getInputStream());
OutputStream out=response.getOutputStream();
ImageIO.write(image, "jpg", out);
}catch(Exception e){
throw e;
}finally{
logger.debug("get()--DownLoadImage-->end");
}
}
public static String toUtf8String(String s) { // 设置编码格式,防止图片中文名称乱码等。
StringBuffer sb = new StringBuffer();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c >= 0 && c <= 255) {
sb.append(c);
} else {
byte[] b;
try {
b = Character.toString(c).getBytes("utf-8");
} catch (Exception ex) {
b = new byte[0];
}
for (int j = 0; j < b.length; j++) {
int k = b[j];
if (k < 0)
k += 256;
sb.append("%" + Integer.toHexString(k).toUpperCase());
}
}
}
return sb.toString();
}
方法三:图片先上传到FTP服务器上,然后通过图片id去下载。其实跟方法二差不多,ftp这里支持多种格式下载。
private void doDownLoadResFile() throws Exception{
HttpServletResponse resp = getResponse();
logger.debug("doDownLoadResFile()-->start");
String resId = getRequest().getParameter("resId");
if(resId==null || "".equals(resId)){
resp.sendError(HttpURLConnection.HTTP_BAD_REQUEST);
return;
}
logger.debug("doDownLoadResFile()-->resId="+resId);
FTPClient client =null;
try{
TFilePO po = tFileMapper.getByPk(Long.parseLong(resId));
String absolutePath = po.getAbsolutePath();
logger.debug("doDownLoadResFile()-->absolutePath="+absolutePath);
FtpConfig ftpconf = FtpConfigCache.getFtp(po.getFtpId()==null ? APLUS_RESOURCE_SFTP : po.getFtpId());
client = SFtpUtil.getConnection(ftpconf);
byte[] bytes = client.get(absolutePath);
resp.setHeader("Content-Disposition", "attachment; filename="
+ toUtf8String(po.getFileName()));
resp.getOutputStream().write(bytes);
}catch(Exception e){
throw e;
}finally{
SFtpUtil.closeFtp(client);
logger.debug("doDownLoadResFile()-->end");
}
}
如果你是湖南的 欢迎加入 湖南人在深圳-Java群:557651502