SprintBoot 实现上传下载
本人在 .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 实现上传下载的更多相关文章
- Struts的文件上传下载
Struts的文件上传下载 1.文件上传 Struts2的文件上传也是使用fileUpload的组件,这个组默认是集合在框架里面的.且是使用拦截器:<interceptor name=" ...
- 基于Spring Mvc实现的Excel文件上传下载
最近工作遇到一个需求,需要下载excel模板,编辑后上传解析存储到数据库.因此为了更好的理解公司框架,我就自己先用spring mvc实现了一个样例. 基础框架 之前曾经介绍过一个最简单的spring ...
- Android okHttp网络请求之文件上传下载
前言: 前面介绍了基于okHttp的get.post基本使用(http://www.cnblogs.com/whoislcj/p/5526431.html),今天来实现一下基于okHttp的文件上传. ...
- 用Canvas+Javascript FileAPI 实现一个跨平台的图片剪切、滤镜处理、上传下载工具
直接上代码,其中上传功能需要自己配置允许跨域的文件服务器地址~ 或者将html文件贴到您的站点下同源上传也OK. 支持: 不同尺寸图片获取. 原图缩小放大. 原图移动. 选择框大小改变. 下载选中的区 ...
- Javaweb学习笔记——上传下载文件
一.前言 在Javaweb中,上传下载是经常用到的功能,对于文件上传,浏览器在上传的过程中是以流的过程将文件传给服务器,一般都是使用commons-fileupload这个包实现上传功能,因为comm ...
- 服务器文件上传下载(XShell+Xftp)
1.下载XShell安装包+Xftp安装包.百度网盘(XShell):https://pan.baidu.com/s/1eR4PFpS 百度网盘(Xftp):https://pan.baidu.com ...
- springmvc 上传下载
springmvc文件上传下载在网上搜索的代码 参考整理了一份需要使用的jar.commons-fileupload.jar与commons-io-1.4.jar 二个文件 1.表单属性为: enct ...
- 简单Excel表格上传下载,POI
一.废话 Excel表格是office软件中的一员,几乎是使用次数最多的办公软件.所以在java进行企业级应用开发的时候经常会用到对应的上传下载便利办公. 目前,比较常用的实现Java导入.导出Exc ...
- JAVA中使用FTPClient上传下载
Java中使用FTPClient上传下载 在JAVA程序中,经常需要和FTP打交道,比如向FTP服务器上传文件.下载文件,本文简单介绍如何利用jakarta commons中的FTPClient(在c ...
随机推荐
- Django 练习班级管理系统八 -- 上传文件
Form表单上传文件 修改 views.py import os def upload(request): if request.method == 'GET': img_list = models. ...
- Ubuntu18.04.2安装中文输入法
转载请注明出处: BooTurbo https://www.cnblogs.com/booturbo/p/11287557.html 1.英文的Ubuntu系统,首先要安装中文语言,在 Settin ...
- LNK2001 无法解析的外部符号 __imp__CameraCreateSettingPage@24
用VS2017,Release X86进行编译时显示如下错误: 1>CWDMDlg.obj : error LNK2001: 无法解析的外部符号 __imp__CameraGetImageBuf ...
- ssh密钥批量分发
#################以下所有的命令脚本都是在centos7系统上实现,centos6略有不同 客户端使用公钥连接服务器的步骤: 提起ssh我们就能想到的是远程连接,平时我们都是通过密码来 ...
- 201871010104-陈园园《面向对象程序设计(java)》第十六周学习总结
201871010104-陈园园<面向对象程序设计(java)>第十六周学习总结 项目 内容 这个作业属于哪个课程 https://www.cnblogs.com/nwnu-daizh/ ...
- HTTPS各版本安全策略HTTPS1_1_TLS1_0、HTTPS2_TLS1_0、HTTPS2_TLS1_2
来自阿里云 https://help.aliyun.com/document_detail/115169.html HTTPS安全策略 更新时间:2019-04-26 14:49:12 分组 ...
- LG2598/BZOJ1412 「ZJOI2009」狼和羊的故事 最小割
问题描述 LG2598 BZOJ1412 题解 看到要把狼和羊两个物种分开 自然想到最小割. 发现\((x,y)\)可以向上下左右走以获得贡献,所以建边:\((x,y),(x-1,y)\),\((x, ...
- 1-开发共享版APP(搭建指南)-快速搭建到自己的服务器
该APP安装包下载链接: http://www.mnif.cn/appapk/IotDevelopmentVersion/20190820/app-debug.apk 或者扫描二维码下载 注:该下载可 ...
- 调试经验分享-让自己的电脑充当WI-Fi模块,用来抓取连接Wi-Fi模块APP上的通信数据
需求 手头有了厂家的APP和Wi-Fi模块 在已经知道APP是通过TCP连接Wi-Fi模块(8266), 同时也知道了连接的端口号的 情况下如何知道厂家的APP发送给Wi-Fi模块的数据 打开自己的笔 ...
- Umi + Dva的数据传递学习Demo(代码有详细注释)
刚学习时写了篇笔记,以免自己忘记,用了一段时间后,觉得不如做个demo,代码写上注释,方便也在学习umi-dva的同学们理解更好,更容易上手. 这可能是网上注释最多,看了最易理解的学习小指南吧,哈哈. ...