本人在 .NET 转JAVA 的路上 ,也在学习SpringBoot相关知识,这里记录一下在Springboot中实现文件上传下载的核心代码

package com.file.demo.springbootfile;

import com.file.util.ResultUtil;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.apache.tomcat.util.http.fileupload.util.Streams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
/*
* springboot整合vue,文件上传下载
* */
//上传不要用@Controller,用@RestController
@RestController
@RequestMapping("/file")
public class FileController {
private static final Logger logger = LoggerFactory.getLogger(FileController.class);
//在文件中,不用/或者\最好,推荐使用File.separator
private final static String fileDir="files";
private final static String rootPath = System.getProperty("user.home")+ File.separator+fileDir+File.separator; /*
* 文件上传
* */
@RequestMapping("/upload")
public Object uploadFile(@RequestParam("file")MultipartFile[] multipartFiles, final HttpServletResponse response, final HttpServletRequest request){
File fileDir = new File(rootPath);
/*
* exists():测试此抽象路径名表示的文件是否存在
* isDirectory():检查一个对象是否是文件夹
* isFile():判断是否为文件,也可能是文件目录
* */
if(!fileDir.exists() && !fileDir.isDirectory()){
//检查到文件不存在则创建
fileDir.mkdir();//创建文件,一级
fileDir.mkdirs();//创建多级
}
try{
if(multipartFiles != null && multipartFiles.length > 0){
for ( int i = 0;i<multipartFiles.length;i++){
try{
String storagePath = rootPath+multipartFiles[i].getOriginalFilename();
logger.info("上传的文件:" + multipartFiles[i].getName()+","+multipartFiles[i].getContentType()+","
+multipartFiles[i].getOriginalFilename() + ",保持的路径为:" + storagePath);
Streams.copy(multipartFiles[i].getInputStream(), new FileOutputStream(storagePath), true);
}catch (IOException e){
logger.info(ExceptionUtils.getFullStackTrace(e));
}
}
}
}catch (Exception e){
return ResultUtil.error(e.getMessage());
}
return ResultUtil.success("上传成功!");
} /*
* 文件下载
* */
@RequestMapping("/download")
public Object downkiadFile(@RequestParam String fileName,final HttpServletResponse response,final HttpServletRequest request){
OutputStream os = null;
InputStream is = null;
try{
//获取输出流rootPath
os = response.getOutputStream();
//重置输出流
response.reset();
response.setContentType("application/x-download;charset=GBK");
response.setHeader("Content-Disposition", "attachment;filename="+ new String(fileName.getBytes("utf-8"), "iso-8859-1")); //读取流
File f= new File(rootPath+fileName);
is = new FileInputStream(f);
if(is == null){
logger.error("下载文件失败,请检查文件“"+ fileName +"”是否存在");
return ResultUtil.error("下载附件失败,请检查文件“" + fileName + "”是否存在");
}
//复制文件
IOUtils.copy(is,response.getOutputStream());
//刷新缓冲
response.getOutputStream().flush();
}catch (IOException e){
return ResultUtil.error("下载文件失败,error:" + e.getMessage());
}
//文件的关闭在finally中执行
finally {
{
try {
if(is != null){
is.close();
}
}catch (IOException e){
logger.error(ExceptionUtils.getFullStackTrace(e));
}
try{
if(os != null){
os.close();
}
}catch (IOException e){
logger.info(ExceptionUtils.getFullStackTrace(e));
}
}
}
return null;
}
}

源码下载地址: https://github.com/struggle0903/SpringBootfiledemo.git

SprintBoot 实现上传下载的更多相关文章

  1. Struts的文件上传下载

    Struts的文件上传下载 1.文件上传 Struts2的文件上传也是使用fileUpload的组件,这个组默认是集合在框架里面的.且是使用拦截器:<interceptor name=" ...

  2. 基于Spring Mvc实现的Excel文件上传下载

    最近工作遇到一个需求,需要下载excel模板,编辑后上传解析存储到数据库.因此为了更好的理解公司框架,我就自己先用spring mvc实现了一个样例. 基础框架 之前曾经介绍过一个最简单的spring ...

  3. Android okHttp网络请求之文件上传下载

    前言: 前面介绍了基于okHttp的get.post基本使用(http://www.cnblogs.com/whoislcj/p/5526431.html),今天来实现一下基于okHttp的文件上传. ...

  4. 用Canvas+Javascript FileAPI 实现一个跨平台的图片剪切、滤镜处理、上传下载工具

    直接上代码,其中上传功能需要自己配置允许跨域的文件服务器地址~ 或者将html文件贴到您的站点下同源上传也OK. 支持: 不同尺寸图片获取. 原图缩小放大. 原图移动. 选择框大小改变. 下载选中的区 ...

  5. Javaweb学习笔记——上传下载文件

    一.前言 在Javaweb中,上传下载是经常用到的功能,对于文件上传,浏览器在上传的过程中是以流的过程将文件传给服务器,一般都是使用commons-fileupload这个包实现上传功能,因为comm ...

  6. 服务器文件上传下载(XShell+Xftp)

    1.下载XShell安装包+Xftp安装包.百度网盘(XShell):https://pan.baidu.com/s/1eR4PFpS 百度网盘(Xftp):https://pan.baidu.com ...

  7. springmvc 上传下载

    springmvc文件上传下载在网上搜索的代码 参考整理了一份需要使用的jar.commons-fileupload.jar与commons-io-1.4.jar 二个文件 1.表单属性为: enct ...

  8. 简单Excel表格上传下载,POI

    一.废话 Excel表格是office软件中的一员,几乎是使用次数最多的办公软件.所以在java进行企业级应用开发的时候经常会用到对应的上传下载便利办公. 目前,比较常用的实现Java导入.导出Exc ...

  9. JAVA中使用FTPClient上传下载

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

随机推荐

  1. 详解Vue的slot新用法

    摘要: 理解Vue插槽. 作者:前端小智 原文:vue 2.6 中 slot 的新用法 Fundebug经授权转载,版权归原作者所有. 为了保证的可读性,本文采用意译而非直译. 最近发布不久的Vue ...

  2. 7. Transformer-XL原理介绍

    1. 语言模型 2. Attention Is All You Need(Transformer)算法原理解析 3. ELMo算法原理解析 4. OpenAI GPT算法原理解析 5. BERT算法原 ...

  3. python--微信小程序“跳一跳‘外挂

    参考网站:http://blog.csdn.net/LittleBeautiful/article/details/78955792 0x00:准备工具: Windows 10: 一个安卓真机 pyt ...

  4. docker-nginx

    docker pull nginx docker run --name nginx -p 8080:80 -d nginx mkdir -p /data/nginx/www /data/nginx/l ...

  5. 201871010117-石欣钰《面向对象程序设计(java)》第七周学习总结

    项目 内容 这个作业属于哪个课程 https://www.cnblogs.com/nwnu-daizh/ 这个作业的要求在哪里 https://www.cnblogs.com/nwnu-daizh/p ...

  6. LeetCode24-Swap_Pairs

    swapPairs public ListNode swapPairs(ListNode head) { if(head==null ||head.next==null) return head; L ...

  7. onchange onpropertychange 和 oninput 事件的区别

    onchange 事件在内容改变(两次内容有可能还是相等的)且失去焦点时触发. onpropertychange 事件却是实时触发,即每增加或删除一个字符就会触发,通过 js 改变也会触发该事件,但是 ...

  8. Oracle工具PLSQL

    2018版的PLSQL美化工具在Tools中的PL/SQL Beautifier中 如下:

  9. Apex 小知识:SOQL 在循环中的应用

    两种在循环中引用 SOQL 的方法 第一种方法: List<Account> accounts = [SELECT Id FROM Account WHERE NumberOfEmploy ...

  10. 阿里云重置CentOS的root默认密码

    问题 今天使用阿里云开了一个云服务器,系统为 CentOS ,远程连接登录时不知道默认root密码 解决方法 在 控制台-实例-操作 中选择 更多-密码/秘钥-重置实例密码 即可