新建io.jsp

  1. <%@ page language="java" contentType="text/html; charset=UTF-8"
  2. pageEncoding="UTF-8"%>
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  4. <html>
  5. <head>
  6. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  7. <title>文件上传</title>
  8. </head>
  9. <body>
  10. <form action="${pageContext.request.contextPath}/testup/uploadBatchFile.do" method="post" enctype="multipart/form-data">
  11. <input type="file" name="files">
  12. <input type="file" name="files">
  13. <button type="submit">上传</button>
  14. </form>
  15. <form action="${pageContext.request.contextPath}/download.do" method="post">
  16. <input name="files" value="SAP接口说明V2.0(1).xlsx">
  17. <button type="submit">下载</button>
  18. </form>
  19. </body>
  20. </html>

  //文件上传控制类 UploadController

  1. package com.zjn.IO;
  2. import java.io.File;
  3. import java.text.SimpleDateFormat;
  4. import java.util.Date;
  5. import java.util.UUID;
  6. import org.springframework.stereotype.Controller;
  7. import org.springframework.web.bind.annotation.RequestMapping;
  8. import org.springframework.web.bind.annotation.RequestMethod;
  9. import org.springframework.web.bind.annotation.RequestParam;
  10. import org.springframework.web.multipart.MultipartFile;
  11. import org.springframework.web.servlet.mvc.support.RedirectAttributes;
  12. @Controller
  13. @RequestMapping("/testup")
  14. public class UploadController {
  15. /**
  16. * 9.②多个文件上传
  17. */
  18. @RequestMapping(value="/uploadBatchFile",method=RequestMethod.POST,consumes="multipart/form-data")
  19. public String uploadBatchFile(@RequestParam MultipartFile[] files,RedirectAttributes redirectAttributes){
  20. boolean isEmpty=true;
  21. try {
  22. for (MultipartFile multipartFile : files) {
  23. if(multipartFile.isEmpty()){
  24. continue;
  25. }
  26. String time=new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
  27. String fileName=multipartFile.getOriginalFilename();
  28. String destFileName="D:\\whupload"+File.separator+time+"_"+fileName;
  29. File destFile=new File(destFileName);
  30. multipartFile.transferTo(destFile);
  31. isEmpty=false;
  32. }
  33. //int i=1/0;
  34. //localhost:8086/test/index?message=upload file success
  35. //redirectAttributes.addAttribute("message","upload file success.");
  36.  
  37. } catch (Exception e) {
  38. // TODO Auto-generated catch block
  39. redirectAttributes.addFlashAttribute("message", "文件上传失败");
  40. System.out.println(e.getMessage());
  41. return "redirect:message.do";
  42. }
  43. if(isEmpty){
  44. redirectAttributes.addFlashAttribute("message", "上传文件为空");
  45. }else{
  46. redirectAttributes.addFlashAttribute("message", "文件上传成功");
  47. }
  48. return "redirect:message.do";
  49. }
  50. @RequestMapping("/message")
  51. public String message() {
  52. return "message";
  53. }
  54. /**
  55. * @Method: makeFileName
  56. * @Description: 生成上传文件的文件名,文件名以:uuid+"_"+文件的原始名称
  57. * @param filename 文件的原始名称
  58. * @return uuid+"_"+文件的原始名称
  59. */
  60. private String makeFileName(String filename){ //2.jpg
  61. //为防止文件覆盖的现象发生,要为上传文件产生一个唯一的文件名
  62. return UUID.randomUUID().toString() + "_" + filename;
  63. }
  64.  
  65. }

  //文件下载控制类 DownController

  1. package com.zjn.IO;
  2. import java.io.File;
  3. import java.io.FileInputStream;
  4. import java.io.IOException;
  5. import java.io.InputStream;
  6. import java.io.OutputStream;
  7. import java.net.URLEncoder;
  8. import javax.servlet.http.HttpServletResponse;
  9. import org.springframework.stereotype.Controller;
  10. import org.springframework.ui.Model;
  11. import org.springframework.web.bind.annotation.RequestMapping;
  12. @Controller
  13. public class DownController {
  14. @RequestMapping(value = "/download")
  15. public String download(HttpServletResponse response, Model model,String files) throws Exception {
  16. System.out.println("进入文件下载》》》》》》》》》》》》》》》》》》files==="+files);
  17. files = new String(files.getBytes("iso8859-1"),"UTF-8");//将iso8859-1编码换成utf-8
  18. System.out.println("转码后files===="+files);
  19. //通过文件名找出文件的所在目录
  20. String URL = "D:\\whupload\\"+files;
  21. //得到要下载的文件
  22. File file = new File(URL);
  23. //如果文件不存在
  24. if(!file.exists()){
  25. //如果文件不存在,进行处理
  26. int i=1/0;//系统会报错,除数不能为0.
  27. // return "modules/cms/front/themes/"+site.getTheme()+"/frontError";
  28. }
  29. InputStream inputStream = null;
  30. OutputStream outputStream = null;
  31. //创建缓冲区
  32. byte[] b= new byte[1024];
  33. int len = 0;
  34. try {
  35. //读取要下载的文件,保存到文件输入流
  36. inputStream = new FileInputStream(file);
  37. outputStream = response.getOutputStream();
  38. response.setContentType("application/force-download");
  39. String filename = file.getName();
  40. //设置响应头,控制浏览器下载该文件
  41. response.addHeader("Content-Disposition","attachment; filename=" + URLEncoder.encode(filename, "UTF-8"));
  42. response.setContentLength( (int) file.length( ) );
  43. //循环将输入流中的内容读取到缓冲区当中
  44. while((len = inputStream.read(b)) != -1){
  45. //输出缓冲区的内容到浏览器,实现文件下载
  46. outputStream.write(b, 0, len);
  47. }
  48. } catch (Exception e) {
  49. e.printStackTrace();
  50. }finally{
  51. if(inputStream != null){
  52. try {
  53. inputStream.close();
  54. inputStream = null;
  55. } catch (IOException e) {
  56. e.printStackTrace();
  57. }
  58. }
  59. if(outputStream != null){
  60. try {
  61. outputStream.close();
  62. outputStream = null;
  63. } catch (IOException e) {
  64. e.printStackTrace();
  65. }
  66. }
  67. }
  68.  
  69. return null;
  70. }
  71. }

  

java中io流实现文件上传下载的更多相关文章

  1. JAVA中使用FTPClient实现文件上传下载

    在JAVA程序中,经常需要和FTP打交道,比如向FTP服务器上传文件.下载文件,本文简单介绍如何利用jakarta commons中的FTPClient(在commons-net包中)实现上传下载文件 ...

  2. JAVA中使用FTPClient实现文件上传下载实例代码

    一.上传文件 原理就不介绍了,大家直接看代码吧 ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 ...

  3. Java 客户端操作 FastDFS 实现文件上传下载替换删除

    FastDFS 的作者余庆先生已经为我们开发好了 Java 对应的 SDK.这里需要解释一下:作者余庆并没有及时更新最新的 Java SDK 至 Maven 中央仓库,目前中央仓库最新版仍旧是 1.2 ...

  4. Java实现FTP批量大文件上传下载篇1

    本文介绍了在Java中,如何使用Java现有的可用的库来编写FTP客户端代码,并开发成Applet控件,做成基于Web的批量.大文件的上传下载控件.文章在比较了一系列FTP客户库的基础上,就其中一个比 ...

  5. Java实现FTP与SFTP文件上传下载

    添加依赖Jsch-0.1.54.jar <!-- https://mvnrepository.com/artifact/com.jcraft/jsch --> <dependency ...

  6. SpringMVC中使用 MultipartFile 进行文件上传下载及删除

    一:引入必要的包 <!--文件上传--> <!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fil ...

  7. java操作FTP,实现文件上传下载删除操作

    上传文件到FTP服务器: /** * Description: 向FTP服务器上传文件 * @param url FTP服务器hostname * @param port FTP服务器端口,如果默认端 ...

  8. java中的文件上传下载

    java中文件上传下载原理 学习内容 文件上传下载原理 底层代码实现文件上传下载 SmartUpload组件 Struts2实现文件上传下载 富文本编辑器文件上传下载 扩展及延伸 学习本门课程需要掌握 ...

  9. java web 文件上传下载

    文件上传下载案例: 首先是此案例工程的目录结构:

随机推荐

  1. day100:MoFang:用户模型类的创建&Marshmallow模块&使用基本构造器Schema完成数据的序列化转换和反序列化转换

    目录 1.用户模型的创建 2.Marshmallow模块 3.MarshMallow基本构造器:Schema 1.基于Schema完成数据序列化转换 2.基于Schema完成数据反序列化转换 3.反序 ...

  2. java中的强引用(Strong reference),软引用(SoftReference),弱引用(WeakReference),虚引用(PhantomReference)

    之前在看深入理解Java虚拟机一书中第一次接触相关名词,但是并不理解,只知道Object obj = new Object()类似这种操作的时候,obj就是强引用.强引用不会被gc回收直到gc roo ...

  3. Rest Framework:序列化组件

    Django内置的serializers(把对象序列化成json字符串 from django.core import serializers def test(request): book_list ...

  4. idea使用帮助

    IDEA激活码形式,扫码二维码回复 激活码 自提,秒激活,持续更新.回复的是> 激活码 2020.2以上版本的 IDEA 请跳转至该链接:https://t.1yb.co/3ntg 2018.3 ...

  5. apache、nginx、Tomcat、IIS引擎解析漏洞

                                            引擎解析漏洞 常见的web容器有IIS.Apache.Nginx.Tomcat等,以下是详细讲解 IIS IIS简介 是 ...

  6. LeetCode初级算法之数组:122 买卖股票的最佳时机 II

    买卖股票的最佳时机 II 题目地址:https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-ii/ 给定一个数组,它的第 i ...

  7. Springcloud之gateway配置及swagger集成

    前言 关于引入gateway的好处我网上找了下: 性能:API高可用,负载均衡,容错机制. 安全:权限身份认证.脱敏,流量清洗,后端签名(保证全链路可信调用),黑名单(非法调用的限制). 日志:日志记 ...

  8. go学习的第7天

    不容易啊,坚持7天了呢,今天开始看视频学习 https://www.bilibili.com/video/BV1pt41127FZ?from=search&seid=4441824587572 ...

  9. 【Alpha冲刺阶段】Scrum Meeting Daily5

    [Alpha冲刺阶段]Scrum Meeting Daily5 1.会议简述 会议开展时间 2020/5/27 8:30-9:00 PM 会议基本内容摘要 大家讲述了自己的任务完成情况以及遇到的问题 ...

  10. WordCounter项目(基于javase)

    1.  Github项目地址: https://github.com/Flyingwater101/WordCount 1.  PSP表格 PSP2.1 Personal Software Proce ...