java文件下载
Java实现HTTP文件下载 (转载)
public void addItem(String url, String filename) {
vDownLoad.add(url);
vFileList.add(filename);
}
/**
* 根据列表下载资源
private Vector vFileList = new Vector(); //下载后的保存文件名列表
/**
* 构造方法
*/
public SaveFile() {}
/**
* 清除下载列表
*/
public void resetList() {
url = (String) vDownLoad.get(i);
filename = (String) vFileList.get(i);
try {
saveToFile(url, filename);
} catch (IOException err) {
if (DEBUG) {
System.out.println("资源[" + url + "]下载失败!!!");
}
vDownLoad.clear();
vFileList.clear();
}
/**
* 增加下载列表项
*
* @param url String
* @param filename String
int size = 0;
//建立链接
url = new URL(destUrl);
httpUrl = (HttpURLConnection) url.openConnection();
Java从服务器下载文件到本地(页面、后台、配置都有)
Java从服务器下载⽂件到本地(页⾯、后台、配置都有)先来看实现效果:有⼀个链接如下:点击链接下载⽂件:第⼀种⽅法:Servlet实现⼀、HTML页⾯部分:1、HTML页⾯中的⼀个链接<a id="downloadTemplate" style="color:blue" onclick="download();">下载导⼊模板</a>2、引⼊JSfunction download(){downloadTemplate('downloadExel.downloadexcel', 'filename', 'project');}/*** ⽤于下载导⼊模板时的影藏form表单的提交,采⽤post⽅式提交* @param action action映射地址* @param type parameter的名称* @param value parameter的值,这⾥为file的filename*/function downloadTemplate(action, type, value){var form = document.createElement('form');document.body.appendChild(form);form.style.display = "none";form.action = action;form.id = 'excel';form.method = 'post';var newElement = document.createElement("input");newElement.setAttribute("type","hidden"); = type;newElement.value = value;form.appendChild(newElement);form.submit();}3、解释上⾯JS(不是正是代码)相当于提交⼀个form,⾥⾯如下:<input type=hidden name="filename" value = "project">后台可以通过下⾯代码获得⽂件名:projectString filename = request.getParameter("filename");(这段是上⾯js的翻译,不是正式的哦)配置前台页⾯和后台交互1、web.xml配置<?xml version="1.0" encoding="UTF-8"?><web-app id="WebApp_ID" version="2.4"xmlns="/xml/ns/j2ee"xmlns:xsi="/2001/XMLSchema-instance"xsi:schemaLocation="/xml/ns/j2ee /xml/ns/j2ee/web-app_2_4.xsd"><servlet><servlet-name>downloadServlet</servlet-name><servlet-class>com.zit.rfid.app.prms.business.service.servlet.DownloadTemplateServlet</servlet-class><load-on-startup>3</load-on-startup></servlet><servlet-mapping><servlet-name>downloadServlet</servlet-name><url-pattern>*.downloadexcel</url-pattern></servlet-mapping></web-app>我这个web.xml不是整个⼯程的web.xml,只是⼀个模块的,在你的web.xml加⼊上⾯servlet和servlet-mapping⾥的内容即可如上:(1)接受 *.downloadexcel 的Action(2)HTML的JS⾥的Action,交给com.test.DownloadTemplateServlet这个类去处理2、WebContent⽬录下新建file⽂件夹,存放project.xls⽂件(Eclipse的Web⼯程有WebContent,MyEclipse好像是WebRoot)三、后台部分1、新建⼀个servlet: DownloadTemplateServlet.javapackage com.test;import java.io.DataInputStream;import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.io.OutputStream;import java.io.OutputStreamWriter;import .URLEncoder;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;/*** @author 022******** 主要⽤于下载导⼊模板,页⾯上传⼊的request中parameter中,filename代表了要下载的模板的名称*/public class DownloadTemplateServlet extends HttpServlet {/**private static final long serialVersionUID = -4541729035831587727L;private final static String HOME_PATH = DownloadTemplateServlet.class.getResource("/").getPath();private final static String DOWNLOAD_TEMP_FILE = HOME_PATH.subSequence(0, HOME_PATH.indexOf("WEB-INF")) + "file/"; @Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {doPost(req, resp);}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {String filename = req.getParameter("filename");try{resp.reset();// 清空输出流String resultFileName = filename + System.currentTimeMillis() + ".xls";resultFileName = URLEncoder.encode(resultFileName,"UTF-8");resp.setCharacterEncoding("UTF-8");resp.setHeader("Content-disposition", "attachment; filename=" + resultFileName);// 设定输出⽂件头resp.setContentType("application/msexcel");// 定义输出类型//输⼊流:本地⽂件路径DataInputStream in = new DataInputStream(new FileInputStream(new File(DOWNLOAD_TEMP_FILE + filename + ".xls")));//输出流OutputStream out = resp.getOutputStream();//输出⽂件int bytes = 0;byte[] bufferOut = new byte[1024];while ((bytes = in.read(bufferOut)) != -1) {out.write(bufferOut, 0, bytes);}out.close();in.close();} catch(Exception e){e.printStackTrace();resp.reset();try {OutputStreamWriter writer = new OutputStreamWriter(resp.getOutputStream(), "UTF-8");String data = "<script language='javascript'>alert(\"\\u64cd\\u4f5c\\u5f02\\u5e38\\uff01\");</script>";writer.write(data);writer.close();} catch (IOException e1) {e1.printStackTrace();}}}}⼤致步骤:1. 获取服务器⽂件所在路径2. 输⼊服务器⽂件3. 输出⽂件到本地第⼆种⽅法:SpringMVC实现这种⽅法⽐较简单⼀、JSP页⾯部分<a id="downloadTemplate" style="color:blue" onclick="download();">下载导⼊模板</a>//导出模板下载function download(){//后台⽅法、⽂件类型、⽂件名downloadTemplate('${pageContext.request.contextPath}/cardIssueVehicleInfo/exportVehicleInfo', 'filename', 'test'); }/*** ⽤于下载导⼊模板时的影藏form表单的提交,采⽤post⽅式提交* @param action 请求后台⽅法* @param type ⽂件类型* @param value ⽂件名*/function downloadTemplate(action, type, value){var form = document.createElement('form');document.body.appendChild(form);form.style.display = "none";form.action = action;form.id = 'excel';form.method = 'post';var newElement = document.createElement("input");newElement.setAttribute("type","hidden"); = type;newElement.value = value;form.appendChild(newElement);form.submit();}⼆、后台部分@RequestMapping("exportVehicleInfo")public void exportVehicleInfo(HttpServletRequest req, HttpServletResponse resp) {String filename = req.getParameter("filename");DataInputStream in = null;OutputStream out = null;try{resp.reset();// 清空输出流String resultFileName = filename + System.currentTimeMillis() + ".xls";resultFileName = URLEncoder.encode(resultFileName,"UTF-8");resp.setCharacterEncoding("UTF-8");resp.setHeader("Content-disposition", "attachment; filename=" + resultFileName);// 设定输出⽂件头resp.setContentType("application/msexcel");// 定义输出类型//输⼊流:本地⽂件路径in = new DataInputStream(new FileInputStream(new File(downloadPath + "test.xls")));//输出流out = resp.getOutputStream();//输出⽂件int bytes = 0;byte[] bufferOut = new byte[1024];while ((bytes = in.read(bufferOut)) != -1) {out.write(bufferOut, 0, bytes);}} catch(Exception e){e.printStackTrace();resp.reset();try {OutputStreamWriter writer = new OutputStreamWriter(resp.getOutputStream(), "UTF-8");String data = "<script language='javascript'>alert(\"\\u64cd\\u4f5c\\u5f02\\u5e38\\uff01\");</script>";writer.write(data);writer.close();} catch (IOException e1) {e1.printStackTrace();}}finally {if(null != in) {try {in.close();} catch (IOException e) {e.printStackTrace();}if(null != out) {try {out.close();} catch (IOException e) { e.printStackTrace(); }}}}。
java实现FTP文件上传与文件下载
java实现FTP⽂件上传与⽂件下载本⽂实例为⼤家分享了两种java实现FTP⽂件上传下载的⽅式,供⼤家参考,具体内容如下第⼀种⽅式:package com.cloudpower.util;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import .TelnetInputStream;import .TelnetOutputStream;import .ftp.FtpClient;/*** Java⾃带的API对FTP的操作* @Title:Ftp.java* @author: 周玲斌*/public class Ftp {/*** 本地⽂件名*/private String localfilename;/*** 远程⽂件名*/private String remotefilename;/*** FTP客户端*/private FtpClient ftpClient;/*** 服务器连接* @param ip 服务器IP* @param port 服务器端⼝* @param user ⽤户名* @param password 密码* @param path 服务器路径* @author 周玲斌* @date 2012-7-11*/public void connectServer(String ip, int port, String user,String password, String path) {try {/* ******连接服务器的两种⽅法*******///第⼀种⽅法// ftpClient = new FtpClient();// ftpClient.openServer(ip, port);//第⼆种⽅法ftpClient = new FtpClient(ip);ftpClient.login(user, password);// 设置成2进制传输ftpClient.binary();System.out.println("login success!");if (path.length() != 0){//把远程系统上的⽬录切换到参数path所指定的⽬录ftpClient.cd(path);}ftpClient.binary();} catch (IOException ex) {ex.printStackTrace();throw new RuntimeException(ex);}}/*** 关闭连接* @author 周玲斌* @date 2012-7-11*/public void closeConnect() {try {ftpClient.closeServer();System.out.println("disconnect success");} catch (IOException ex) {System.out.println("not disconnect");ex.printStackTrace();throw new RuntimeException(ex);}}/*** 上传⽂件* @param localFile 本地⽂件* @param remoteFile 远程⽂件* @author 周玲斌* @date 2012-7-11*/public void upload(String localFile, String remoteFile) {this.localfilename = localFile;this.remotefilename = remoteFile;TelnetOutputStream os = null;FileInputStream is = null;try {//将远程⽂件加⼊输出流中os = ftpClient.put(this.remotefilename);//获取本地⽂件的输⼊流File file_in = new File(this.localfilename);is = new FileInputStream(file_in);//创建⼀个缓冲区byte[] bytes = new byte[1024];int c;while ((c = is.read(bytes)) != -1) {os.write(bytes, 0, c);}System.out.println("upload success");} catch (IOException ex) {System.out.println("not upload");ex.printStackTrace();throw new RuntimeException(ex);} finally{try {if(is != null){is.close();}} catch (IOException e) {e.printStackTrace();} finally {try {if(os != null){os.close();}} catch (IOException e) {e.printStackTrace();}}}}/*** 下载⽂件* @param remoteFile 远程⽂件路径(服务器端)* @param localFile 本地⽂件路径(客户端)* @author 周玲斌* @date 2012-7-11*/public void download(String remoteFile, String localFile) {TelnetInputStream is = null;FileOutputStream os = null;try {//获取远程机器上的⽂件filename,借助TelnetInputStream把该⽂件传送到本地。
Java文件上传与文件下载实现方法详解
Java⽂件上传与⽂件下载实现⽅法详解本⽂实例讲述了Java⽂件上传与⽂件下载实现⽅法。
分享给⼤家供⼤家参考,具体如下:Java⽂件上传数据上传是客户端向服务器端上传数据,客户端向服务器发送的所有请求都属于数据上传。
⽂件上传是数据上传的⼀种特例,指客户端向服务器上传⽂件。
即将保存在客户端的⽂件上传⼀个副本到服务器,并保存在服务器中。
1、上传表单要求⽂件上传要求客户端提交特殊的请求——multipart请求,即包含多部分数据的请求。
必须将<form/>标签的enctype属性值设为“multipart/form-data”,enctype表⽰encodingType,及编码类型由于客户端上传⽂件的⼤⼩是不确定的,所以http协议规定,⽂件上传的数据要存放于请求正⽂中,不能出现在URL地址栏内。
也就是说,想要上传⽂件必须提交POST请求。
表单中要有<input type="file" />标签注意:multipart/form-data请求与普通请求不同2、下载⽂件上传jar包并查看官⽅⽂档选择Commons中的FileUpload项⽬,并下载jar包和源⽂件查看FileUpload的⼯作⽅式查看FileUpload项⽬的API3、使⽤第三⽅jar包上传⽂件public class RegisterServlet extends HttpServlet {private static final long serialVersionUID = 1L;public RegisterServlet() {super();}protected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {response.getWriter().append("Served at: ").append(request.getContextPath());}protected void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {//第⼀步、判断请求是否为multipart请求if(!ServletFileUpload.isMultipartContent(request)) {throw new RuntimeException("当前请求只⽀持⽂件上传");}try {//第⼆步、创建FileItem⼯⼚DiskFileItemFactory factory = new DiskFileItemFactory();//设置临时⽂件存储⽬录String path = this.getServletContext().getRealPath("/Temp");File temp = new File(path);factory.setRepository(temp);//单位:字节。
java实现文件上传和下载
java实现⽂件上传和下载本⽂实例为⼤家分享了java实现⽂件上传和下载的具体代码,供⼤家参考,具体内容如下⽂件的上传upload:⽂件上传客户端通过表单的⽂件域file 把客户端的⽂件上传保存到服务器的硬盘上页⾯⾸先对上传的表单有以下要求:必须有⽂件域:input type=file表单提交⽅式:method=post表单的 enctype=multipart/form-data<form method="post" action="/user/regist" enctype="multipart/form-data"><table style="border: chartreuse;solid:2px"><tr><th>⽤户名</th><td><input type="text" name="username"></td></tr><tr><th>密码</th><td><input type="password" name="password"></td></tr><tr><th>⽤户头像</th><td><input type="file" name="photo"> </td></tr><tr><td colspan="2"><input type="submit" value="提交"></td></tr></table></form>Servlet1)⾸先要导⼊以下两个jar包,通过commons-fileupload实现⽂件上传2)创建⼀个⼯⼚对象DiskFileItemFactory,在创建⼀个多部件表单解析器ServletFileUpload,构造⽅法传⼊⼯⼚对象3)解析器解析请求对象,获得⼀个list集合,其中list集合存储的是⼀个⼀个的fileItem对象,⼀个fileItem对应⼀个组件,也就是⼀个<input>4) 遍历集合⽤isFormField()⽅法判断是否为普通组件,然后着重处理⽂件域组件5)获取⽂件名,并⽤getRealPath⽅法获取服务器上传⽂件所在路径,创建新⽂件夹6)获取输⼊流和创建输出流,进⾏⽂件的读写@WebServlet(value = "/user/regist")public class UploadServlet extends HttpServlet {protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {//创建⼀个⼯⼚对象DiskFileItemFactory factory = new DiskFileItemFactory();//创建⼀个多部件解析器对象ServletFileUpload fileUpload = new ServletFileUpload(factory);User user = new User();FileOutputStream out=null;try {//⽤解析器对象解析请求,返回⼀个FileItem类型的集合List<FileItem> list = fileUpload.parseRequest(req);for (FileItem fileItem : list) {/*** fileItem.getFieldName());:::获取组件的name值* fileItem.getName());::::获取⽂件域的⽂件名* fileItem.getSize());::::获取数据的字节个数* fileItem.getString());::::获取数据的字符串* fileItem.isFormField());:::判断是否为普通组件*///判断部件是否为普通组件if (fileItem.isFormField()) {//普通组件//获取组件名字也就是name的值String fieldName = fileItem.getFieldName();//获取组件的值也就是value的值String value = fileItem.getString("utf-8");if ("username".equals(fieldName)) { //设置实体类的属性user.setUsername(value);} else if ("password".equals(fieldName)) {user.setPassword(value);}} else {// ⽂件域//获取⽂件名String fielName = fileItem.getName();//输⼊流来读数据InputStream in = fileItem.getInputStream();//设置⽂件写出的路径,并⽤随机码来保证图⽚可以重复String path=req.getServletContext().getRealPath("/imgs/"+ UUID.randomUUID()+fielName);System.out.println("⽂件路径为:"+path);File file = new File(path);out = new FileOutputStream(file);//利⽤commons-io-1.4.jar的IOUtils的copy⽅法直接实现⽂件的复制IOUtils.copy(in,out);user.setPhoto(file.getName());}}} catch (Exception e) {e.printStackTrace();}finally {if(out!=null){out.close();}}req.getSession().setAttribute("user",user);req.getRequestDispatcher("/sucess.jsp").forward(req,resp);}}⽂件的下载页⾯只需⼀个超链接,传需要下载的⽂件名,或者直接输⼊路径在浏览器例: <a href="<c:url value='/file/download?fileName=14.jpg'/>" >狗狗1</a><br/>Servlet1)接收参数,获取⽂件名2)获取imgs的路径,也就是存储⽂件的⽂件夹的路径,然后创建⽂件,传⼊该路径和⽂件名3)创建输⼊流读取⽂件4)设置响应头,⾸先根据⽂件名字获取⽂件的⼤类型,设置响应头Content-Type指定响应的类型;设置响应头Content-Disposition,指定⽂件以附件形式保存到本地磁盘5)⽤响应获取输出流,读出⽂件到客户端@WebServlet("/user/download")public class DownloadServlet extends HttpServlet {protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {request.setCharacterEncoding("UTF-8");//获取要下载的⽂件名String fileName = request.getParameter("fileName");System.out.println(fileName);//获取服务器中存储图⽚的⽂件夹的路径String path1 = request.getServletContext().getRealPath("/imgs");String path=path1+"/"+fileName;File file = new File(path);//创建输⼊流读⽂件FileInputStream in = new FileInputStream(file);//通过⽂件名字获取⽂件的⼤类型String type = request.getServletContext().getMimeType(fileName);//设置响应头ContentType指定响应内容的类型response.setHeader("Content-type",type);//设置响应头Content-Disposition 指定以附件形式保存响应的信息response.setHeader("Content-Disposition","attachment;filename="+(URLEncoder.encode(fileName, "utf-8"))); ServletOutputStream out = response.getOutputStream();//实现⽂件的读写IOUtils.copy(in,out);if(in!=null){in.close();}}}以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。
java下载功能
java下载功能Java是一种跨平台的编程语言,能够在各种操作系统上运行,因此非常适合用于开发具有下载功能的应用程序。
Java提供了丰富的API和库,使开发者能够轻松地实现下载功能。
下面是一些常用的Java下载功能的实现方式:1. 使用URLConnection类来进行下载:URLConnection类是Java提供的用于网络连接的类,可以通过该类来实现下载。
使用URLConnection的步骤包括创建URL对象、打开连接、获取输入流、创建输出流、将数据从输入流写入输出流等。
2. 使用HttpClient库来进行下载:HttpClient是一个功能强大的开源HTTP客户端库,可以用于发送HTTP请求并处理HTTP响应。
通过使用HttpClient库,可以实现更为复杂的下载功能,例如断点续传、多线程下载等。
3. 使用多线程来进行下载:在下载大文件时,为了加快下载速度,可以使用多线程来并行下载。
通过将文件分成多个部分,每个部分由一个线程负责下载,可以同时下载多个部分,提高下载速度。
4. 使用下载管理器来进行下载:下载管理器是一种用于管理下载任务的工具,可以对下载任务进行管理和控制,例如暂停、取消、进度监控等。
Java提供了一些第三方库,如Downpour 和Download4j,可以用于实现下载管理器。
5. 使用流式处理来进行下载:在Java中,可以使用流式处理来处理大文件的下载。
通过使用BufferedInputStream和BufferedOutputStream,可以将下载的文件分块读取并写入本地文件,避免一次性读取整个文件导致内存溢出。
总之,Java提供了多种方式来实现下载功能,开发者可以根据需求选择合适的方法来实现。
通过合理利用Java的API和库,能够实现高效、安全的下载功能,并提供给用户优质的下载体验。
Java中文件上传下载--使用Minio
Java中⽂件上传下载--使⽤Minio Minio模板类:@RequiredArgsConstructorpublic class MinioTemplate implements InitializingBean {private final String endpoint;private final String accessKey;private final String secretKey;private MinioClient client;/*** 创建bucket** @param bucketName bucket名称*/@SneakyThrowspublic void createBucket(String bucketName) {if (!client.bucketExists(bucketName)) {client.makeBucket(bucketName);}}/*** 获取全部bucket* <p>* https://docs.minio.io/cn/java-client-api-reference.html#listBuckets*/@SneakyThrowspublic List<Bucket> getAllBuckets() {return client.listBuckets();}/*** 根据bucketName获取信息* @param bucketName bucket名称*/@SneakyThrowspublic Optional<Bucket> getBucket(String bucketName) {return client.listBuckets().stream().filter(b -> ().equals(bucketName)).findFirst();}/*** 根据bucketName删除信息* @param bucketName bucket名称*/@SneakyThrowspublic void removeBucket(String bucketName) {client.removeBucket(bucketName);}/*** 根据⽂件前置查询⽂件** @param bucketName bucket名称* @param prefix 前缀* @param recursive 是否递归查询* @return MinioItem 列表*/@SneakyThrowspublic List<MinioItem> getAllObjectsByPrefix(String bucketName, String prefix, boolean recursive) {List<MinioItem> objectList = new ArrayList<>();Iterable<Result<Item>> objectsIterator = client.listObjects(bucketName, prefix, recursive);while (objectsIterator.iterator().hasNext()) {objectList.add(new MinioItem(objectsIterator.iterator().next().get()));}return objectList;}/*** 获取⽂件外链** @param bucketName bucket名称* @param objectName ⽂件名称* @param expires 过期时间 <=7* @return url*/@SneakyThrowspublic String getObjectURL(String bucketName, String objectName, Integer expires) {return client.presignedGetObject(bucketName, objectName, expires);}/*** 获取⽂件** @param bucketName bucket名称* @param objectName ⽂件名称* @return ⼆进制流*/@SneakyThrowspublic InputStream getObject(String bucketName, String objectName) {return client.getObject(bucketName, objectName);}/*** 上传⽂件** @param bucketName bucket名称* @param objectName ⽂件名称* @param stream ⽂件流* @throws Exception https://docs.minio.io/cn/java-client-api-reference.html#putObject*/public void putObject(String bucketName, String objectName, InputStream stream) throws Exception {client.putObject(bucketName, objectName, stream, stream.available(), "application/octet-stream");}/*** 上传⽂件** @param bucketName bucket名称* @param objectName ⽂件名称* @param stream ⽂件流* @param size ⼤⼩* @param contextType 类型* @throws Exception https://docs.minio.io/cn/java-client-api-reference.html#putObject*/public void putObject(String bucketName, String objectName, InputStream stream, long size, String contextType) throws Exception { client.putObject(bucketName, objectName, stream, size, contextType);}/*** 获取⽂件信息** @param bucketName bucket名称* @param objectName ⽂件名称* @throws Exception https://docs.minio.io/cn/java-client-api-reference.html#statObject*/public ObjectStat getObjectInfo(String bucketName, String objectName) throws Exception {return client.statObject(bucketName, objectName);}/*** 删除⽂件** @param bucketName bucket名称* @param objectName ⽂件名称* @throws Exception https://docs.minio.io/cn/java-client-api-reference.html#removeObject*/public void removeObject(String bucketName, String objectName) throws Exception {client.removeObject(bucketName, objectName);}@Overridepublic void afterPropertiesSet() throws Exception {Assert.hasText(endpoint, "Minio url 为空");Assert.hasText(accessKey, "Minio accessKey为空");Assert.hasText(secretKey, "Minio secretKey为空");this.client = new MinioClient(endpoint, accessKey, secretKey);}⽂件上传⽅法:public String upload(@RequestParam("file") MultipartFile file) {String fileName = file.getOriginalFilename();Map<String, String> resultMap = new HashMap<>(4);resultMap.put("bucketName", "bucketName");resultMap.put("fileName", fileName);try {minioTemplate.putObject("bucketName", fileName, file.getInputStream()); } catch (Exception e) {return "上传失败";}return "上传成功";}⽂件下载⽅法:public void download(String fileName, HttpServletResponse response, HttpServletRequest request) { String userAgent = request.getHeader("User-Agent");String[] nameArray = StrUtil.split(fileName, "-");try (InputStream inputStream = minioTemplate.getObject(nameArray[0], nameArray[1])) {//解决乱码if ( //IE 8 ⾄ IE 10userAgent.toUpperCase().contains("MSIE") ||//IE 11userAgent.contains("Trident/7.0")) {fileName = .URLEncoder.encode(nameArray[1], "UTF-8");} else{fileName = new String(nameArray[1].getBytes("UTF-8"),"iso-8859-1");}response.setHeader("Content-Disposition", "attachment;filename=" + fileName);response.setContentType("application/force-download");response.setCharacterEncoding("UTF-8");IoUtil.copy(inputStream, response.getOutputStream());} catch (Exception e) {log.error("⽂件读取异常", e);}}。
java实现高效下载文件的方法
java实现⾼效下载⽂件的⽅法本⽂实例为⼤家分享了java实现下载⽂件的⽅法,供⼤家参考,具体内容如下本⽂我们介绍⼏种⽅法下载⽂件。
从基本JAVA IO 到 NIO包,也介绍第三⽅库的⼀些⽅法,如Async Http Client 和 Apache Commons IO.最后我们还讨论在连接断开后如何恢复下载。
使⽤java IO下载⽂件最基本的⽅法是java IO,使⽤URL类打开待下载⽂件的连接。
为有效读取⽂件,我们使⽤openStream() ⽅法获取InputStream:BufferedInputStream in = new BufferedInputStream(new URL(FILE_URL).openStream())当从InputStream读取⽂件时,强烈建议使⽤BufferedInputStream去包装InputStream,⽤于提升性能。
使⽤缓存可以提升性能。
read⽅法每次读⼀个字节,每次⽅法调⽤意味着系统调⽤底层的⽂件系统。
当JVM调⽤read()⽅法时,程序执⾏上下⽂将从⽤户模式切换到内核模式并返回。
从性能的⾓度来看,这种上下⽂切换⾮常昂贵。
当我们读取⼤量字节时,由于涉及⼤量上下⽂切换,应⽤程序性能将会很差。
为了读取URL的字节并写⾄本地⽂件,需要使⽤FileOutputStream 类的write⽅法:try (BufferedInputStream in = new BufferedInputStream(new URL(FILE_URL).openStream());FileOutputStream fileOutputStream = new FileOutputStream(FILE_NAME)) {byte dataBuffer[] = new byte[1024];int bytesRead;while ((bytesRead = in.read(dataBuffer, 0, 1024)) != -1) {fileOutputStream.write(dataBuffer, 0, bytesRead);}} catch (IOException e) {// handle exception}使⽤BufferedInputStream,read⽅法按照我们设置缓冲器⼤⼩读取⽂件。
Java创建文件夹、创建文件、上传文件,下载文件
Java创建⽂件夹、创建⽂件、上传⽂件,下载⽂件1、创建⽂件夹/*** 判断⽂件夹是否存在* @param myPath*/public static void judeDirExists(File myPath) {if (!myPath.exists()) {myPath.mkdirs();//多级⽂件夹⽬录//myPpath.mkdir();//单级⽂件夹⽬录System.out.println("创建⽂件夹路径为:"+ myPath.getPath());}}2、修改⽂件夹名称/*** 通过⽂件路径直接修改⽂件名* @param filePath 需要修改的⽂件的完整路径* @param newFileName 需要修改的⽂件的名称* @return*/private static String modifyFileName(String filePath, String newFileName) {File f = new File(filePath);if (!f.exists()) { // 判断原⽂件是否存在return null;}newFileName = newFileName.trim();if ("".equals(newFileName)) // ⽂件名不能为空return null;String newFilePath = null;if (f.isDirectory()) { // 判断是否为⽂件夹newFilePath = filePath.substring(0, stIndexOf("/")) + "/" + newFileName;} else {newFilePath = filePath.substring(0, stIndexOf("/"))+ "/" + newFileName + filePath.substring(stIndexOf("."));}File nf = new File(newFilePath);if (!f.exists()) { // 判断需要修改为的⽂件是否存在(防⽌⽂件名冲突)return null;}try {f.renameTo(nf); // 修改⽂件名} catch(Exception err) {err.printStackTrace();return null;}return newFilePath;}3、⽂件附件形式下载/*** 下载⽂档⽂件* @param request* @param response* @param file_name* @throws IOException*/@RequestMapping(value = "/download_dex_privacy.do/{file_name}")public void downloadDexDoc(@PathVariable("file_name") String file_name,HttpServletRequest request, HttpServletResponse response) throws IOException { String path=request.getServletContext().getRealPath("/WEB-INF/classes/dex_doc");System.out.println(path);File file=new File(path+"/"+file_name);// 获取输⼊流InputStream bis = new BufferedInputStream(new FileInputStream(file));// 假如以中⽂名下载的话// 转码,免得⽂件名中⽂乱码file_name = URLEncoder.encode(file_name, "UTF-8");// 设置⽂件下载头response.addHeader("Content-Disposition", "attachment;filename=" + file_name);// 1.设置⽂件ContentType类型,这样设置,会⾃动判断下载⽂件类型response.setContentType("multipart/form-data");BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());int len = 0;while ((len = bis.read()) != -1) {out.write(len);out.flush();}out.close();}4、上传⽂件/*** 添⽤户收款⽅式信息* @param receipt* @return*/@RequestMapping(value = "add.json")@ResponseBodypublic ReturnReceipt addReceipt(@RequestParam("file") MultipartFile file, String fundsPassword, Receipt receipt,HttpServletRequest request, HttpServletResponse response) { BasePage_Model pageModel=SetDefaultPage(request);ReturnReceipt returnReceipt=new ReturnReceipt();if(er_cookie_model.phone==null){try {response.sendRedirect("/login");return null;} catch (IOException e) {logger.error("ReceiptController==>addReceipt==>未登录跳转异常==>"+e.getMessage());}}if (file.isEmpty()) {returnReceipt.status=ReturnReceipt.status_102;returnReceipt.message="上传失败,请选择⽂件";}else{ReceiptMode receiptMode=new ReceiptMode();receiptMode.id=receipt.receiptModeId;ReturnReceiptMode returnReceiptMode=receiptModeDao.queryReceiptModeById(receiptMode);if(returnReceiptMode.status==ReturnReceiptMode.status_100){ReceiptMode receipt_mode=returnReceiptMode.receipt_mode;String fileName= er_cookie_model.phone+DateUtil.getTimeStamp();boolean file_state=uploadFile(file,receipt_,fileName);if(file_state){Receipt _receipt=new Receipt();_receipt.phone=er_cookie_model.phone;_receipt.receiptModeId=receipt.receiptModeId;_receipt.receiptInfo=receipt.receiptInfo+","+fileName;ReturnReceipt _returnReceipt=receiptDao.addReceipt(_receipt);returnReceipt.status=_returnReceipt.status;returnReceipt.message=_returnReceipt.message;}else{returnReceipt.status=ReturnReceipt.status_103;returnReceipt.message="添加收款⽅式⾮法操作";}}else{returnReceipt.status=ReturnReceipt.status_103;returnReceipt.message="添加收款⽅式⾮法操作";}}return returnReceipt;}public boolean uploadFile(MultipartFile file,String receiptName,String fileName){String filePath = ConfigDefault.receipt_mode_url + "/" + receiptName + "/";File dir = new File(filePath);if (!dir.exists()) {dir.mkdirs();}File dest = new File(filePath + fileName + ".png");try {file.transferTo(dest);return true;} catch (IOException e) {logger.error("ReceiptController==>uploadFile==>IOException==>" + e.getMessage());return false;}}5、。
java实现文件下载.
在BlogJava上已经有一位作者阐述了文件上传的问题, 地址是在Struts 2中实现文件上传 , 因此我就不再讨论那个话题了。
我今天简单介绍一下Struts 2的文件下载问题。
我们的项目名为 struts2hello ,所使用的开发环境是MyEclipse 6,当然其实用哪个 IDE 都 是一样的,只要把类库放进去就行了,文件下载不需要再加入任何额外的包。
读者可以参考 文档:http://beansoft.java/myeclipse_doc_cn/struts2_demo.pdf ,来了解怎么下载 和配置基本的 Struts 2开发环境。
为了便于大家对比,我把完整的 struts.xml 的配置信息列出来:Xml代码1 <?xml version="1.0" encoding="UTF-8" ?>2 <!DOCTYPE struts PUBLIC3 "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"4 "/dtds/struts-2.0.dtd">56 <struts>7 <package name="default" extends="struts-default" >8 <!-- 在这里添加 Action 定义 -->910 <!-- 简单文件下载 -->11 <action name="download" class="example.FileDownloadAction">12 <result name="success" type="stream">13 <param name="contentType">text/plain</param>14 <param name="inputName">inputStream</param>15 <paramname="contentDisposition">attachment;filename="struts2中文.txt"</param>16 <param name="bufferSize">4096</param>17 </result>18 </action>1920 <!-- 文件下载,支持中文附件名 -->21 <action name="download2" class="example.FileDownloadAction2">22 <!-- 初始文件名 -->23 <param name="fileName">Struts 中文附件.txt</param>24 <result name="success" type="stream">25 <param name="contentType">text/plain</param>26 <param name="inputName">inputStream</param>27 <!-- 使用经过转码的文件名作为下载文件名, downloadFileName属性28 对应 action类中的方法 getDownloadFileName() -->29 <paramname="contentDisposition">attachment;filename="${downloadFileName}"</param>30 <param name="bufferSize">4096</param>31 </result>32 </action>3334 <!-- 下载现有文件 -->35 <action name="download3" class="example.FileDownloadAction3">36 <param name="inputPath">/download/系统说明.doc</param>37 <!-- 初始文件名 -->38 <param name="fileName">系统说明.doc</param>39 <result name="success" type="stream">40 <paramname="contentType">application/octet-stream;charset=ISO8859-1</param>41 <param name="inputName">inputStream</param>42 <!-- 使用经过转码的文件名作为下载文件名, downloadFileName属性43 对应 action类中的方法 getDownloadFileName() -->44 <paramname="contentDisposition">attachment;filename="${downloadFileName}"</param>45 <param name="bufferSize">4096</param>46 </result>47 </action>4849 </package>5051 </struts>Xml代码52 <?xml version="1.0" encoding="UTF-8" ?>53 <!DOCTYPE struts PUBLIC54 "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"55 "/dtds/struts-2.0.dtd">5657 <struts>58 <package name="default" extends="struts-default" >59 <!-- 在这里添加 Action 定义 -->6061 <!-- 简单文件下载 -->62 <action name="download" class="example.FileDownloadAction">63 <result name="success" type="stream">64 <param name="<SPAN class=hilite3><SPANstyle="BACKGROUND-COLOR:#aaffaa">contentType</SPAN></SPAN>">text/plain</param>65 <param name="inputName">inputStream</param>66 <paramname="contentDisposition">attachment;filename="<SPAN class=hilite1><SPANstyle="BACKGROUND-COLOR: #ffff00">struts2</SPAN></SPAN>中文.txt"</param>67 <param name="bufferSize">4096</param>68 </result>69 </action>7071 <!-- 文件下载,支持中文附件名 -->72 <action name="download2" class="example.FileDownloadAction2">73 <!-- 初始文件名 -->74 <param name="fileName">Struts 中文附件.txt</param>75 <result name="success" type="stream">76 <param name="<SPAN class=hilite3><SPANstyle="BACKGROUND-COLOR:#aaffaa">contentType</SPAN></SPAN>">text/plain</param>77 <param name="inputName">inputStream</param>78 <!-- 使用经过转码的文件名作为下载文件名, downloadFileName 属性79 对应 action类中的方法 getDownloadFileName() -->80 <paramname="contentDisposition">attachment;filename="${downloadFileName}"</param>81 <param name="bufferSize">4096</param>82 </result>83 </action>8485 <!-- 下载现有文件 -->86 <action name="download3" class="example.FileDownloadAction3">87 <param name="inputPath">/download/系统说明.<SPANclass=hilite5>doc</SPAN></param>88 <!-- 初始文件名 -->89 <param name="fileName">系统说明.<SPANclass=hilite5>doc</SPAN></param>90 <result name="success" type="stream">91 <param name="<SPAN class=hilite3><SPANstyle="BACKGROUND-COLOR:#aaffaa">contentType</SPAN></SPAN>">application/octet-stream;charset=ISO885 9-1</param>92 <param name="inputName">inputStream</param>93 <!-- 使用经过转码的文件名作为下载文件名, downloadFileName 属性94 对应 action类中的方法 getDownloadFileName() -->95 <paramname="contentDisposition">attachment;filename="${downloadFileName}"</param>96 <param name="bufferSize">4096</param>97 </result>98 </action>99100 </package>101102</struts>Struts 2中对文件下载做了直接的支持,相比起自己辛辛苦苦的设置种种HTTP 头来说,现 在实现文件下载无疑要简便的多。
java下载excel文件
java下载excel文件原代码剪切图片:修改后剪切图片:源码:public void downloadTaskModel()throws Exception{HttpServletResponse response = ToftServletContext.getContext().getResponse(); HttpServletRequest request = ToftServletContext.getContext().getRequest();String path = request.getRealPath("/");path = new String(path.getBytes("iso-8859-1"),"GBK");String matches = "[A-Za-z]:\\\\[^:?\"><*]*";if(!path.matches(matches)){throw new Exception("文件路径存在非法字符!");}path = path.replaceAll("\\\\", "/");File file = new File(path+"/templateFile/taskTemplate.xls");if(!file.isFile()||!file.exists()||file.isDirectory()){throw new Exception("下载的文件路径或文件不存在!");}//由于限制了导入模板的类型,所以在导出模板时必须限制。
if(!file.getName().matches(".*\\.(?i)(xls)$")){throw new Exception("当前模板类型有误,只能导出“.xls”格式的excel模板!"); }response.setContentType("application/x-msdownload");response.setContentLength((int)file.length());String taskNme = ClientUtils.getTimeStr(new Date(), "yyyyMMddHHmmss");response.setHeader("Content-Disposition","attachment;filename="+URLEncoder.encode("模板"+taskNme+".xls","UTF-8"));FileInputStream fis = new FileInputStream(file);BufferedInputStream buff = new BufferedInputStream(fis);byte b[] = new byte[1024];long k = 0 ;OutputStream myout = response.getOutputStream();while(k<file.length()){int j = buff.read(b,0,1024);k += j ;myout.write(b,0,j);}myout.flush();myout.close();}。
Java下载文件的四种方式详细代码
Java下载⽂件的四种⽅式详细代码1.以流的⽅式下载public HttpServletResponse download(String path, HttpServletResponse response) {try {// path是指欲下载的⽂件的路径。
File file = new File(path);// 取得⽂件名。
String filename = file.getName();// 取得⽂件的后缀名。
String ext = filename.substring(stIndexOf(".") + 1).toUpperCase();// 以流的形式下载⽂件。
InputStream fis = new BufferedInputStream(new FileInputStream(path));byte[] buffer = new byte[fis.available()];fis.read(buffer);fis.close();// 清空responseresponse.reset();// 设置response的Headerresponse.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));response.addHeader("Content-Length", "" + file.length());OutputStream toClient = new BufferedOutputStream(response.getOutputStream());response.setContentType("application/octet-stream");toClient.write(buffer);toClient.flush();toClient.close();} catch (IOException ex) {ex.printStackTrace();}return response;}2.下载本地⽂件public void downloadLocal(HttpServletResponse response) throws FileNotFoundException {// 下载本地⽂件String fileName = "Operator.doc".toString(); // ⽂件的默认保存名// 读到流中InputStream inStream = new FileInputStream("c:/Operator.doc");// ⽂件的存放路径// 设置输出的格式response.reset();response.setContentType("bin");response.addHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");// 循环取出流中的数据byte[] b = new byte[100];int len;try {while ((len = inStream.read(b)) > 0)response.getOutputStream().write(b, 0, len);inStream.close();} catch (IOException e) {e.printStackTrace();}}3.下载⽹络⽂件public void downloadNet(HttpServletResponse response) throws MalformedURLException {// 下载⽹络⽂件int bytesum = 0;int byteread = 0;URL url = new URL("/logo.gif");try {URLConnection conn = url.openConnection();InputStream inStream = conn.getInputStream();FileOutputStream fs = new FileOutputStream("c:/abc.gif");byte[] buffer = new byte[1204];int length;while ((byteread = inStream.read(buffer)) != -1) {bytesum += byteread;System.out.println(bytesum);fs.write(buffer, 0, byteread);}} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}4.⽀持在线打开的⽅式public void downLoad(String filePath, HttpServletResponse response, boolean isOnLine) throws Exception {File f = new File(filePath);if (!f.exists()) {response.sendError(404, "File not found!");return;}BufferedInputStream br = new BufferedInputStream(new FileInputStream(f));byte[] buf = new byte[1024];int len = 0;response.reset(); // ⾮常重要if (isOnLine) { // 在线打开⽅式URL u = new URL("file:///" + filePath);response.setContentType(u.openConnection().getContentType());response.setHeader("Content-Disposition", "inline; filename=" + f.getName());// ⽂件名应该编码成UTF-8} else { // 纯下载⽅式response.setContentType("application/x-msdownload");response.setHeader("Content-Disposition", "attachment; filename=" + f.getName());}OutputStream out = response.getOutputStream();while ((len = br.read(buf)) > 0)out.write(buf, 0, len);br.close();out.close();}到此这篇关于Java下载⽂件的四种⽅式详细代码的⽂章就介绍到这了。
java通过http方式下载文件
java通过http⽅式下载⽂件package com.qiyi;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.io.PrintWriter;import .URL;import .URLConnection;import java.util.List;import java.util.Map;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import .HttpURLConnection;import .URL;import java.io.File;import java.io.IOException;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;public class HttpRequest {/*** 从⽹络Url中下载⽂件* @param urlStr* @param fileName* @param savePath* @throws IOException*/public static void downLoadFromUrl(String urlStr,String fileName,String savePath,String toekn) throws IOException{ URL url = new URL(urlStr);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)");conn.setRequestProperty("lfwywxqyh_token",toekn);//得到输⼊流InputStream inputStream = conn.getInputStream();//获取⾃⼰数组byte[] getData = readInputStream(inputStream);//⽂件保存位置File saveDir = new File(savePath);if(!saveDir.exists()){saveDir.mkdir();}File file = new File(saveDir+File.separator+fileName);FileOutputStream fos = new FileOutputStream(file);fos.write(getData);if(fos!=null){fos.close();}if(inputStream!=null){inputStream.close();}System.out.println("info:"+url+" download success");}/*** 从输⼊流中获取字节数组* @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();}}package com.qiyi;import java.io.IOException;public class Main {public static void main(String[] args) throws IOException {// write your code here;//String url="http://127.0.0.1:9001/abc/notice/export?startDate=2017-1-27&endDate=2017-12-31";String token="v32Eo2Tw+qWI/eiKW3D8ye7l19mf1NngRLushO6CumLMHIO1aryun0/Y3N3YQCv/TqzaO/TFHw4=";// String token="SiGBCH6QblUHs7NiouV09rL6uAA3Sv0cGicaSxJiC/78DoWIMzVbW6VCwwkymYsZaxndDkYqkm4="; HttpRequest.downLoadFromUrl(url,"abc.xls","D:\\",token);System.out.println("下载完成");}}。
javaweb如何实现文件下载功能?
javaweb如何实现⽂件下载功能?⼀、超链接下载:这种⽅式⾮常简单,就是在超链接⾥⾯写上即将下载的⽂件路径,我这⾥将⽂件放在webapp下⾯的download⽂件夹⾥⾯:<a href="download/notice1.pdf"></a>但是有⼀个弊端就是,如果下载的⽂件可以直接被浏览器识别就会⾃动打开,⽐如.png,.pdf⽂件,如果是.zip等⽂件,则不会打开。
⼆、Servlet下载:为了解决第⼀种⽅式的弊端,我们采取Servlet下载⽅式。
1.新建Servlet⽂件,可以命名为DownloadServlet,映射url是“/downloadServlet”,我的项⽬名称是suiningAdmissions;2.在DownloadServlet中加⼊以下内容,其中filename是你在下载的时候需要传递的参数,是你即将下载的⽂件的名称;package cn.itIcey.suining.web.servlet;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.FileInputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;@WebServlet("/downloadServlet")public class DownloadServlet extends HttpServlet {protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//获得请求⽂件名String filename = request.getParameter("filename");System.out.println(filename);//设置⽂件MIME类型response.setContentType(getServletContext().getMimeType(filename));//设置Content-Dispositionresponse.setHeader("Content-Disposition", "attachment;filename="+filename);//读取⽬标⽂件,通过response将⽬标⽂件写到客户端//获取⽬标⽂件的绝对路径String fullFileName = getServletContext().getRealPath("/download/" + filename);//System.out.println(fullFileName);//读取⽂件InputStream in = new FileInputStream(fullFileName);OutputStream out = response.getOutputStream();byte[] buffer = new byte[1024];int len;//循环取出流中的数据while((len = in.read(buffer)) != -1){out.write(buffer,0,len);}in.close();out.close();}protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {this.doPost(request, response);}}3.将下载链接重新设置,其中/suiningAdmission/downloadServlet是我创建的Servlet的映射路径,注意⼀定要把前⾯的项⽬名称加上去!filename后⾯的内容就是下载的⽂件名称。
Java后台Controller实现文件下载操作
Java后台Controller实现⽂件下载操作代码参数:1.filePath:⽂件的绝对路径(d:\download\a.xlsx)2.fileName(a.xlsx)3.编码格式(GBK)4.response、request不介绍了,从控制器传⼊的http对象代码⽚.//控制器@RequestMapping(UrlConstants.BLACKLIST_TESTDOWNLOAD)public void downLoad(String filePath, HttpServletResponse response, HttpServletRequest request) throws Exception {boolean is = myDownLoad("D:\\a.xlsx","a.xlsx","GBK",response,request);if(is)System.out.println("成功");elseSystem.out.println("失败");}//下载⽅法public boolean myDownLoad(String filePath,String fileName, String encoding, HttpServletResponse response, HttpServletRequest request){ File f = new File(filePath);if (!f.exists()) {try {response.sendError(404, "File not found!");} catch (IOException e) {e.printStackTrace();}return false;}String type = fileName.substring(stIndexOf(".") + 1);//判断下载类型 xlsx 或 xls 现在只实现了xlsx、xls两个类型的⽂件下载if (type.equalsIgnoreCase("xlsx") || type.equalsIgnoreCase("xls")){response.setContentType("application/force-download;charset=UTF-8");final String userAgent = request.getHeader("USER-AGENT");try {if (StringUtils.contains(userAgent, "MSIE") || StringUtils.contains(userAgent, "Edge")) {// IE浏览器fileName = URLEncoder.encode(fileName, "UTF8");} else if (StringUtils.contains(userAgent, "Mozilla")) {// google,⽕狐浏览器fileName = new String(fileName.getBytes(), "ISO8859-1");} else {fileName = URLEncoder.encode(fileName, "UTF8");// 其他浏览器}response.setHeader("Content-disposition", "attachment; filename=" + fileName);} catch (UnsupportedEncodingException e) {logger.error(e.getMessage(), e);return false;}InputStream in = null;OutputStream out = null;try {//获取要下载的⽂件输⼊流in = new FileInputStream(filePath);int len = 0;//创建数据缓冲区byte[] buffer = new byte[1024];//通过response对象获取outputStream流out = response.getOutputStream();//将FileInputStream流写⼊到buffer缓冲区while((len = in.read(buffer)) > 0) {//使⽤OutputStream将缓冲区的数据输出到浏览器out.write(buffer,0,len);}//这⼀步⾛完,将⽂件传⼊OutputStream中后,页⾯就会弹出下载框} catch (Exception e) {logger.error(e.getMessage(), e);return false;} finally {try {if (out != null)out.close();if(in!=null)in.close();} catch (IOException e) {logger.error(e.getMessage(), e);}}return true;}else {logger.error("不⽀持的下载类型!");return false;}}实现效果1.⽕狐浏览器效果2.chrome效果,⾃动下载补充知识:⽂件上传/下载的⼏种写法(java后端)⽂件上传1、框架已经帮你获取到⽂件对象File了public boolean uploadFileToLocale(File uploadFile,String filePath) { boolean ret_bl = false;try {InputStream in = new FileInputStream(uploadFile);ret_bl=copyFile(in,filePath);} catch (Exception e) {e.printStackTrace();}return ret_bl;}public boolean copyFile(InputStream in,String filePath) {boolean ret_bl = false;FileOutputStream os=null;try {os = new FileOutputStream(filePath,false);byte[] b = new byte[8 * 1024];int length = 0;while ((length = in.read(b)) > 0) {os.write(b, 0, length);}os.close();in.close();ret_bl = true;} catch (Exception e) {e.printStackTrace();}finally{try {if(os!=null){os.close();}if(in!=null){in.close();}} catch (IOException e) {e.printStackTrace();}}return ret_bl;}}2、天了个撸,SB架构师根本就飘在天空没下来,根本就没想⽂件上传这⼀回事public String uploadByHttp(HttpServletRequest request) throws Exception{String filePath=null;List<String> fileNames = new ArrayList<>();//创建⼀个通⽤的多部分解析器CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());//判断 request 是否有⽂件上传,即多部分请求if(multipartResolver.isMultipart(request)){//转换成多部分requestMultipartHttpServletRequest multiRequest =multipartResolver.resolveMultipart(request);MultiValueMap<String,MultipartFile> multiFileMap = multiRequest.getMultiFileMap();List<MultipartFile> fileSet = new LinkedList<>();for(Entry<String, List<MultipartFile>> temp : multiFileMap.entrySet()){fileSet = temp.getValue();}String rootPath=System.getProperty("user.dir");for(MultipartFile temp : fileSet){filePath=rootPath+"/tem/"+temp.getOriginalFilename();File file = new File(filePath);if(!file.exists()){file.mkdirs();}fileNames.add(temp.getOriginalFilename());temp.transferTo(file);}}}3、神啊,我正在撸框架,请问HttpServletRequest怎么获取(1)在web.xml中配置⼀个监听<listener><listener-class>org.springframework.web.context.request.RequestContextListener</listener-class></listener>(2)HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();⽂件下载(直接⽤链接下载的不算),这⽐较简单1、本地⽂件下载(即⽂件保存在本地)public void fileDownLoad(HttpServletRequest request,HttpServletResponse response,String fileName,String filePath) throws Exception {response.setCharacterEncoding("UTF-8");//设置ContentType字段值response.setContentType("text/html;charset=utf-8");//通知浏览器以下载的⽅式打开response.addHeader("Content-type", "appllication/octet-stream");response.addHeader("Content-Disposition", "attachment;filename="+fileName);//通知⽂件流读取⽂件InputStream in = request.getServletContext().getResourceAsStream(filePath);//获取response对象的输出流OutputStream out = response.getOutputStream();byte[] buffer = new byte[1024];int len;//循环取出流中的数据while((len = in.read(buffer)) != -1){out.write(buffer,0,len);}}2、远程⽂件下载(即⽹上资源下载,只知道⽂件URI)public static void downLoadFromUrl(String urlStr,String fileName,HttpServletResponse response){try {urlStr=urlStr.replaceAll("\\\\", "/");URL url = new URL(urlStr);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();response.reset();response.setContentType("application/octet-stream; charset=utf-8");response.setHeader("Content-Disposition", "attachment; filename=" + new String(fileName.getBytes("GBK"),"ISO8859_1"));//获取响应报⽂输出流对象//获取response对象的输出流OutputStream out = response.getOutputStream();byte[] buffer = new byte[1024];int len;//循环取出流中的数据while((len = in.read(buffer)) != -1){out.write(buffer,0,len);}} catch (Exception e) {e.printStackTrace();}}以上这篇Java后台Controller实现⽂件下载操作就是⼩编分享给⼤家的全部内容了,希望能给⼤家⼀个参考,也希望⼤家多多⽀持。
Java实现浏览器下载文件及文件预览
Java实现浏览器下载⽂件及⽂件预览插曲想记录⼀下,以后可以来粘贴复制⽤。
⼀、浏览器下载⽂件setContentType() 该实体头的作⽤是让服务器告诉浏览器它发送的数据属于什么⽂件类型。
没有缓存response.addHeader("Pargam", "no-cache");response.addHeader("Cache-Control", "no-cache");public static void setResponseHeader(HttpServletResponse response, String name) {try {name = new String(name.getBytes(), "ISO8859-1");} catch (UnsupportedEncodingException e) {e.printStackTrace();}response.setContentType("application/docx");//要保存的⽂件名response.setHeader("Content-Disposition", "attachment;filename=" + name + ".docx");response.addHeader("Pargam", "no-cache");response.addHeader("Cache-Control", "no-cache");}⼆、浏览器预览⽂件只需要把下⾯这⾏注释就好response.setHeader("Content-Disposition", "attachment;filename=" + name + ".docx");setContentType() 中的参数选择:⽂件扩展名Content-Type(Mime-Type)⽂件扩展名Content-Type(Mime-Type).*(⼆进制流,不知道下载⽂件类型)application/octet-stream.tif image/tiff.001application/x-001.301application/x-301.323text/h323.906application/x-906.907drawing/907.a11application/x-a11.acp audio/x-mei-aac.ai application/postscript.aif audio/aiff.aifc audio/aiff.aiff audio/aiff.anv application/x-anv.asa text/asa.asf video/x-ms-asf.asp text/asp.asx video/x-ms-asf.au audio/basic.avi video/avi.awf application/ text/xml.bmp application/x-bmp.bot application/x-bot.c4t application/x-c4t.c90application/x-c90.cal application/x-cals.cat application/vnd.ms-pki.seccat .cdf application/x-netcdf.cdr application/x-cdr.cel application/x-cel.cer application/x-x509-ca-cert.cg4application/x-g4.cgm application/x-cgm.cit application/x-cit.class java/*.cml text/xml.cmp application/x-cmp.cmx application/x-cmx.cot application/x-cot.crl application/pkix-crl.crt application/x-x509-ca-cert.csi application/x-csi.css text/css.cut application/x-cut.dbf application/x-dbf.dbm application/x-dbm.dbx application/x-dbx.dcd text/xml.dcx application/x-dcx.der application/x-x509-ca-cert.dgn application/x-dgn.dib application/x-dib.dll application/x-msdownload.doc application/msword.dot application/msword.drw application/x-drw.dtd text/xml.dwf Model/vnd.dwf.dwf application/x-dwf.dwg application/x-dwg.dxb application/x-dxb.dxf application/x-dxf.edn application/vnd.adobe.edn.emf application/x-emf.eml message/rfc822.ent text/xml.epi application/x-epi.eps application/x-ps.eps application/postscript.etd application/x-ebx.exe application/x-msdownload.fax image/fax.fdf application/vnd.fdf.fif application/fractals.fo text/xml.frm application/x-frm.g4application/x-g4.gbr application/x-gbr.application/x-.gif image/gif.gl2application/x-gl2.gp4application/x-gp4.hgl application/x-hgl.hmr application/x-hmr.hpg application/x-hpgl.hpl application/x-hpl.hqx application/mac-binhex40.hrf application/x-hrf.hta application/hta.htc text/x-component.htm text/html.html text/html.htt text/webviewhtml.htx text/html.icb application/x-icb.ico image/x-icon.ico application/x-ico.iff application/x-iff.ig4application/x-g4.igs application/x-igs.iii application/x-iphone.img application/x-img.ins application/x-internet-signup .isp application/x-internet-signup.IVF video/x-ivf.java java/*.jfif image/jpeg.jpe image/jpeg.jpe application/x-jpe.jpeg image/jpeg.jpg image/jpeg.jpg application/x-jpg.js application/x-javascript.jsp text/1audio/x-liquid-file.lar application/tex application/x-latex.lavs audio/x-liquid-secure.lbm application/x-lbm.lmsff audio/x-la-lms.ls application/x-javascript.ltr application/x-ltr.m1v video/x-mpeg.m2v video/x-mpeg.m3u audio/mpegurl.m4e video/mpeg4.mac application/x-mac.man application/x-troff-man.math text/xml.mdb application/msaccess.mdb application/x-mdb.mfp application/x-shockwave-flash.mht message/rfc822.mhtml message/rfc822.mi application/x-mi.mid audio/mid.midi audio/mid.mil application/x-mil.mml text/xml.mnd audio/x-musicnet-download.mns audio/x-musicnet-stream.mocha application/x-javascript.movie video/x-sgi-movie.mp1audio/mp1.mp2audio/mp2.mp2v video/mpeg.mp3audio/mp3.mp4video/mpeg4.mpa video/x-mpg.mpd application/vnd.ms-project.mpe video/x-mpeg.mpeg video/mpg.mpg video/mpg.mpga audio/rn-mpeg.mpp application/vnd.ms-project.mps video/x-mpeg.mpt application/vnd.ms-project.mpv video/mpg.mpv2video/mpeg.mpw application/vnd.ms-project.mpx application/vnd.ms-project.mtx text/xml.mxp application/x-mmxp.net image/pnetvue.nrf application/x-nrf.nws message/rfc822.odc text/x-ms-odc.out application/x-out.p10application/pkcs10.p12application/x-pkcs12.p7b application/x-pkcs7-certificates .p7c application/pkcs7-mime.p7m application/pkcs7-mime.p7r application/x-pkcs7-certreqresp.p7s application/pkcs7-signature.pc5application/x-pc5.pci application/x-pci.pcl application/x-pcl.pcx application/x-pcx.pdf application/pdf.pdf application/pdf.pdx application/vnd.adobe.pdx.pfx application/x-pkcs12.pgl application/x-pgl.pic application/x-pic.pko application/vnd.ms-pki.pko.pl application/x-perl.plg text/html.pls audio/scpls.plt application/x-plt.png image/png.png application/x-png.pot application/vnd.ms-powerpoint .ppa application/vnd.ms-powerpoint.ppm application/x-ppm.pps application/vnd.ms-powerpoint.ppt application/vnd.ms-powerpoint .ppt application/x-ppt.pr application/x-pr.prf application/pics-rules.prn application/x-prn.prt application/x-prt.ps application/x-ps.ps application/postscript.ptn application/x-ptn.pwz application/vnd.ms-powerpoint.r3t text/vnd.rn-realtext3d.ra audio/vnd.rn-realaudio.ram audio/x-pn-realaudio.ras application/x-ras.rat application/rat-file.rdf text/xml.rec application/vnd.rn-recording.red application/x-red.rgb application/x-rgb.rjs application/vnd.rn-realsystem-rjs.rjt application/vnd.rn-realsystem-rjt .rlc application/x-rlc.rle application/x-rle.rm application/vnd.rn-realmedia.rmf application/vnd.adobe.rmf.rmi audio/mid.rmj application/vnd.rn-realsystem-rmj.rmm audio/x-pn-realaudio.rmp application/vnd.rn-rn_music_package.rms application/vnd.rn-realmedia-secure.rmvb application/vnd.rn-realmedia-vbr .rmx application/vnd.rn-realsystem-rmx.rnx application/vnd.rn-realplayer.rp image/vnd.rn-realpix.rpm audio/x-pn-realaudio-plugin.rsml application/vnd.rn-rsml.rt text/vnd.rn-realtext.rtf application/msword.rtf application/x-rtf.rv video/vnd.rn-realvideo.sam application/x-sam.sat application/x-sat.sdp application/sdp.sdw application/x-sdw.sit application/x-stuffit.slb application/x-slb.sld application/x-sld.slk drawing/x-slk.smi application/smil.smil application/smil.smk application/x-smk.snd audio/basic.sol text/plain.sor text/plain.spc application/x-pkcs7-certificates .spl application/futuresplash.spp text/xml.ssm application/streamingmedia.sst application/vnd.ms-pki.certstore .stl application/vnd.ms-pki.stl.stm text/html.sty application/x-sty.svg text/xml.swf application/x-shockwave-flash.tdf application/x-tdf.tg4application/x-tg4.tga application/x-tga.tif image/tiff.tif application/x-tif.tiff image/tiff.tld text/xml.top drawing/x-top.torrent application/x-bittorrent.tsd text/xml.txt text/plain.uin application/x-icq.uls text/iuls.vcf text/x-vcard.vda application/x-vda.vdx application/vnd.visio.vml text/xml.vpg application/x-vpeg005.vsd application/vnd.visio.vsd application/x-vsd.vss application/vnd.visio.vst application/vnd.visio.vst application/x-vst.vsw application/vnd.visio.vsx application/vnd.visio.vtx application/vnd.visio.vxml text/xml.wav audio/wav.wax audio/x-ms-wax.wb1application/x-wb1.wb2application/x-wb2.wb3application/x-wb3.wbmp image/vnd.wap.wbmp.wiz application/msword.wk3application/x-wk3.wk4application/x-wk4.wkq application/x-wkq.wks application/x-wks.wm video/x-ms-wm.wma audio/x-ms-wma.wmd application/x-ms-wmd.wmf application/x-wmf.wml text/vnd.wap.wml.wmv video/x-ms-wmv.wmx video/x-ms-wmx.wmz application/x-ms-wmz.wp6application/x-wp6.wpd application/x-wpd.wpg application/x-wpg.wpl application/vnd.ms-wpl.wq1application/x-wq1.wr1application/x-wr1.wri application/x-wri.wrk application/x-wrk.ws application/x-ws.ws2application/x-ws.wsc text/scriptlet.wsdl text/xml.wvx video/x-ms-wvx.xdp application/vnd.adobe.xdp.xdr text/xml.xfd application/vnd.adobe.xfd.xfdf application/vnd.adobe.xfdf.xhtml text/html.xls application/vnd.ms-excel.xls application/x-xls.xlw application/x-xlw.xml text/xml.xpl audio/scpls.xq text/xml.xql text/xml.xquery text/xml.xsd text/xml.xsl text/xml.xslt text/xml.xwd application/x-xwd.x_b application/x-x_b.sis application/vnd.symbian.install.sisx application/vnd.symbian.install .x_t application/x-x_t.ipa application/vnd.iphone.apk application/vnd.android.package-archive.xap application/x-silverlight-appJava 后台字符串以txt⽂件响应到浏览器进⾏下载String fileName = "短信模版.txt";OutputStream os = null;try {response.reset();response.setContentType("application/octet-stream; charset=utf-8");response.setHeader("Content-Disposition", "attachment; filename=" + new String(fileName.getBytes(),"ISO8859-1")); byte[] bytes = sb.toString().getBytes("GBK");os = response.getOutputStream();// 将字节流传⼊到响应流⾥,响应到浏览器os.write(bytes);os.close();} catch (Exception ex) {logger.error("导出失败:", ex);throw new RuntimeException("导出失败");}finally {try {if (null != os) {os.close();}} catch (IOException ioEx) {logger.error("导出失败:", ioEx);}}以上为个⼈经验,希望能给⼤家⼀个参考,也希望⼤家多多⽀持。
Java中都通用文件下载(ContentType、文件头、response、out四步骤)
Java中都通⽤⽂件下载(ContentType、⽂件头、response、out四步骤)我们就直接切⼊主题啦,⽂件下载只需要四步:1.设置⽂件ContentType类型2.设置⽂件头3.通过response获取ServletOutputStream对象(out)4.写到输出流(out)中下载代码:这⾥我使⽤的是SpringMVC,不过它在这⾥的唯⼀⽤途就是⽤来获取ServletContext对象,这个对象的⽤途,下⾯实例中有说明下载,需要⽤到两个jar包:commons-fileupload.jar和commons-io.jarJava代码1. import org.springframework.stereotype.Controller;2. import org.springframework.web.bind.annotation.RequestMapping;3. import org.springframework.web.context.ServletContextAware;4.5. import javax.servlet.ServletContext;6. import javax.servlet.ServletOutputStream;7. import javax.servlet.http.HttpServletResponse;8. import java.io.*;9.10. @Controller11. public class FileController implements ServletContextAware{12. //Spring这⾥是通过实现ServletContextAware接⼝来注⼊ServletContext对象13. private ServletContext servletContext;14.15.16. @RequestMapping("file/download")17. public void fileDownload(HttpServletResponse response){18. //获取⽹站部署路径(通过ServletContext对象),⽤于确定下载⽂件位置,从⽽实现下载19. String path = servletContext.getRealPath("/");20.21. //1.设置⽂件ContentType类型,这样设置,会⾃动判断下载⽂件类型22. response.setContentType("multipart/form-data");23. //2.设置⽂件头:最后⼀个参数是设置下载⽂件名(假如我们叫a.pdf)24. response.setHeader("Content-Disposition", "attachment;fileName="+"a.pdf");25. ServletOutputStream out;26. //通过⽂件路径获得File对象(假如此路径中有⼀个download.pdf⽂件)27. File file = new File(path + "download/" + "download.pdf");28.29. try {30. FileInputStream inputStream = new FileInputStream(file);31.32. //3.通过response获取ServletOutputStream对象(out)33. out = response.getOutputStream();34.35. int b = 0;36. byte[] buffer = new byte[512];37. while (b != -1){38. b = inputStream.read(buffer);39. //4.写到输出流(out)中40. out.write(buffer,0,b);41. }42. inputStream.close();43. out.close();44. out.flush();45.46. } catch (IOException e) {47. e.printStackTrace();48. }49. }50.51. @Override52. public void setServletContext(ServletContext servletContext) {53. this.servletContext = servletContext;54. }55. }。
用Java语言实现文件的下载
用Java语言实现文件的下载
李玲;李宇丽
【期刊名称】《长春光学精密机械学院学报》
【年(卷),期】1998(021)002
【摘要】介绍了Java网络通信方面的内容。
在基于HTTP、FTP协议的前提下,运用Java丰富的类库,完成了文件的下载,并对网络安全性做了初步的探讨。
【总页数】5页(P66-70)
【作者】李玲;李宇丽
【作者单位】长春邮电学院计算机工程系;长春邮电学院计算机工程系
【正文语种】中文
【中图分类】TP393
【相关文献】
1.一种能实现文件权限控制的文件上传下载系统 [J], 秦高德
2.浅谈在JSP中实现文件下载以及统计下载次数 [J], 孙青格乐
3.用Java语言在机顶盒实现符合MHP规范的文件和目录对象的接收 [J], 鞠啸东;郑世宝
4.利用java语言实现文件上传功能 [J], 王文龙;王武魁
5.用JAVA语言实现GIF图像文件的编码 [J], 贝雨馨;徐晓霞
因版权原因,仅展示原文概要,查看原文内容请购买。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
}catch (Exception e) {
// TODO: handle exception
}
}
bos.write(buffer, 0, len);
}
bos.close();
return bos.toByteArray();
}
public static void main(String[] args) {
}
if(inputStream!=null){
inputStream.close();
}
System.out.println("info:"+url+" download success");
try{
downLoadFromUrl("http://101.95.48.97:8005/res/upload/interface/apptutorials/manualstypeico/6f83ce8f-0da5-49b3-bac8-fd5fc67d2725.png",
//防止屏蔽程序抓取而返回403错误
conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
//得到输入流
byte[] buffer = new byte[1024];
int len = 0;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
while((len = inputStream.read(buffer)) != -1) {
/**
* 从网络Url中下载文件
* @param urlStr
* @param fileName
* @param savePath
* @throws IOException
*/
public static void downLoadFromUrl(String urlStr,String fileName,String savePath) throws IOException{
}
/**
* 从输入流中获取字节数组
* @param inputStream
* @return
* @throws IOException
*/
public static byte[] readInputStream(InputStream inputStream) throws IOException {
InputStream inputStream = conn.getInputStream();
//获取自己数ห้องสมุดไป่ตู้
byte[] getData = readInputStream(inputStream);
//文件保存位置
FileOutputStream fos = new FileOutputStream(file);
fos.write(getData);
if(fos!=null){
fos.close();
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
//设置超时间为3秒
conn.setConnectTimeout(3*1000);
File saveDir = new File(savePath);
if(!saveDir.exists()){
saveDir.mkdir();
}
File file = new File(saveDir+File.separator+fileName);