java中io流实现文件上传下载
新建io.jsp
- <%@ page language="java" contentType="text/html; charset=UTF-8"
- pageEncoding="UTF-8"%>
- <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
- <title>文件上传</title>
- </head>
- <body>
- <form action="${pageContext.request.contextPath}/testup/uploadBatchFile.do" method="post" enctype="multipart/form-data">
- <input type="file" name="files">
- <input type="file" name="files">
- <button type="submit">上传</button>
- </form>
- <form action="${pageContext.request.contextPath}/download.do" method="post">
- <input name="files" value="SAP接口说明V2.0(1).xlsx">
- <button type="submit">下载</button>
- </form>
- </body>
- </html>
//文件上传控制类 UploadController
- package com.zjn.IO;
- import java.io.File;
- import java.text.SimpleDateFormat;
- import java.util.Date;
- import java.util.UUID;
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RequestMethod;
- import org.springframework.web.bind.annotation.RequestParam;
- import org.springframework.web.multipart.MultipartFile;
- import org.springframework.web.servlet.mvc.support.RedirectAttributes;
- @Controller
- @RequestMapping("/testup")
- public class UploadController {
- /**
- * 9.②多个文件上传
- */
- @RequestMapping(value="/uploadBatchFile",method=RequestMethod.POST,consumes="multipart/form-data")
- public String uploadBatchFile(@RequestParam MultipartFile[] files,RedirectAttributes redirectAttributes){
- boolean isEmpty=true;
- try {
- for (MultipartFile multipartFile : files) {
- if(multipartFile.isEmpty()){
- continue;
- }
- String time=new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
- String fileName=multipartFile.getOriginalFilename();
- String destFileName="D:\\whupload"+File.separator+time+"_"+fileName;
- File destFile=new File(destFileName);
- multipartFile.transferTo(destFile);
- isEmpty=false;
- }
- //int i=1/0;
- //localhost:8086/test/index?message=upload file success
- //redirectAttributes.addAttribute("message","upload file success.");
- } catch (Exception e) {
- // TODO Auto-generated catch block
- redirectAttributes.addFlashAttribute("message", "文件上传失败");
- System.out.println(e.getMessage());
- return "redirect:message.do";
- }
- if(isEmpty){
- redirectAttributes.addFlashAttribute("message", "上传文件为空");
- }else{
- redirectAttributes.addFlashAttribute("message", "文件上传成功");
- }
- return "redirect:message.do";
- }
- @RequestMapping("/message")
- public String message() {
- return "message";
- }
- /**
- * @Method: makeFileName
- * @Description: 生成上传文件的文件名,文件名以:uuid+"_"+文件的原始名称
- * @param filename 文件的原始名称
- * @return uuid+"_"+文件的原始名称
- */
- private String makeFileName(String filename){ //2.jpg
- //为防止文件覆盖的现象发生,要为上传文件产生一个唯一的文件名
- return UUID.randomUUID().toString() + "_" + filename;
- }
- }
//文件下载控制类 DownController
- package com.zjn.IO;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.OutputStream;
- import java.net.URLEncoder;
- import javax.servlet.http.HttpServletResponse;
- import org.springframework.stereotype.Controller;
- import org.springframework.ui.Model;
- import org.springframework.web.bind.annotation.RequestMapping;
- @Controller
- public class DownController {
- @RequestMapping(value = "/download")
- public String download(HttpServletResponse response, Model model,String files) throws Exception {
- System.out.println("进入文件下载》》》》》》》》》》》》》》》》》》files==="+files);
- files = new String(files.getBytes("iso8859-1"),"UTF-8");//将iso8859-1编码换成utf-8
- System.out.println("转码后files===="+files);
- //通过文件名找出文件的所在目录
- String URL = "D:\\whupload\\"+files;
- //得到要下载的文件
- File file = new File(URL);
- //如果文件不存在
- if(!file.exists()){
- //如果文件不存在,进行处理
- int i=1/0;//系统会报错,除数不能为0.
- // return "modules/cms/front/themes/"+site.getTheme()+"/frontError";
- }
- InputStream inputStream = null;
- OutputStream outputStream = null;
- //创建缓冲区
- byte[] b= new byte[1024];
- int len = 0;
- try {
- //读取要下载的文件,保存到文件输入流
- inputStream = new FileInputStream(file);
- outputStream = response.getOutputStream();
- response.setContentType("application/force-download");
- String filename = file.getName();
- //设置响应头,控制浏览器下载该文件
- response.addHeader("Content-Disposition","attachment; filename=" + URLEncoder.encode(filename, "UTF-8"));
- response.setContentLength( (int) file.length( ) );
- //循环将输入流中的内容读取到缓冲区当中
- while((len = inputStream.read(b)) != -1){
- //输出缓冲区的内容到浏览器,实现文件下载
- outputStream.write(b, 0, len);
- }
- } catch (Exception e) {
- e.printStackTrace();
- }finally{
- if(inputStream != null){
- try {
- inputStream.close();
- inputStream = null;
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- if(outputStream != null){
- try {
- outputStream.close();
- outputStream = null;
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- return null;
- }
- }
java中io流实现文件上传下载的更多相关文章
- JAVA中使用FTPClient实现文件上传下载
在JAVA程序中,经常需要和FTP打交道,比如向FTP服务器上传文件.下载文件,本文简单介绍如何利用jakarta commons中的FTPClient(在commons-net包中)实现上传下载文件 ...
- 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 ...
- Java 客户端操作 FastDFS 实现文件上传下载替换删除
FastDFS 的作者余庆先生已经为我们开发好了 Java 对应的 SDK.这里需要解释一下:作者余庆并没有及时更新最新的 Java SDK 至 Maven 中央仓库,目前中央仓库最新版仍旧是 1.2 ...
- Java实现FTP批量大文件上传下载篇1
本文介绍了在Java中,如何使用Java现有的可用的库来编写FTP客户端代码,并开发成Applet控件,做成基于Web的批量.大文件的上传下载控件.文章在比较了一系列FTP客户库的基础上,就其中一个比 ...
- Java实现FTP与SFTP文件上传下载
添加依赖Jsch-0.1.54.jar <!-- https://mvnrepository.com/artifact/com.jcraft/jsch --> <dependency ...
- SpringMVC中使用 MultipartFile 进行文件上传下载及删除
一:引入必要的包 <!--文件上传--> <!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fil ...
- java操作FTP,实现文件上传下载删除操作
上传文件到FTP服务器: /** * Description: 向FTP服务器上传文件 * @param url FTP服务器hostname * @param port FTP服务器端口,如果默认端 ...
- java中的文件上传下载
java中文件上传下载原理 学习内容 文件上传下载原理 底层代码实现文件上传下载 SmartUpload组件 Struts2实现文件上传下载 富文本编辑器文件上传下载 扩展及延伸 学习本门课程需要掌握 ...
- java web 文件上传下载
文件上传下载案例: 首先是此案例工程的目录结构:
随机推荐
- day100:MoFang:用户模型类的创建&Marshmallow模块&使用基本构造器Schema完成数据的序列化转换和反序列化转换
目录 1.用户模型的创建 2.Marshmallow模块 3.MarshMallow基本构造器:Schema 1.基于Schema完成数据序列化转换 2.基于Schema完成数据反序列化转换 3.反序 ...
- java中的强引用(Strong reference),软引用(SoftReference),弱引用(WeakReference),虚引用(PhantomReference)
之前在看深入理解Java虚拟机一书中第一次接触相关名词,但是并不理解,只知道Object obj = new Object()类似这种操作的时候,obj就是强引用.强引用不会被gc回收直到gc roo ...
- Rest Framework:序列化组件
Django内置的serializers(把对象序列化成json字符串 from django.core import serializers def test(request): book_list ...
- idea使用帮助
IDEA激活码形式,扫码二维码回复 激活码 自提,秒激活,持续更新.回复的是> 激活码 2020.2以上版本的 IDEA 请跳转至该链接:https://t.1yb.co/3ntg 2018.3 ...
- apache、nginx、Tomcat、IIS引擎解析漏洞
引擎解析漏洞 常见的web容器有IIS.Apache.Nginx.Tomcat等,以下是详细讲解 IIS IIS简介 是 ...
- LeetCode初级算法之数组:122 买卖股票的最佳时机 II
买卖股票的最佳时机 II 题目地址:https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-ii/ 给定一个数组,它的第 i ...
- Springcloud之gateway配置及swagger集成
前言 关于引入gateway的好处我网上找了下: 性能:API高可用,负载均衡,容错机制. 安全:权限身份认证.脱敏,流量清洗,后端签名(保证全链路可信调用),黑名单(非法调用的限制). 日志:日志记 ...
- go学习的第7天
不容易啊,坚持7天了呢,今天开始看视频学习 https://www.bilibili.com/video/BV1pt41127FZ?from=search&seid=4441824587572 ...
- 【Alpha冲刺阶段】Scrum Meeting Daily5
[Alpha冲刺阶段]Scrum Meeting Daily5 1.会议简述 会议开展时间 2020/5/27 8:30-9:00 PM 会议基本内容摘要 大家讲述了自己的任务完成情况以及遇到的问题 ...
- WordCounter项目(基于javase)
1. Github项目地址: https://github.com/Flyingwater101/WordCount 1. PSP表格 PSP2.1 Personal Software Proce ...