1、在配置文件中添加文件相对路径或者绝对路径

file:upload:path: uploadFile # 相对路径#path2: D://file 绝对路径

2、定义上传下载接口

public interface UploadService {/*** 上传文件,返回地址* @param file* @param request* @return* @throws FileNotFoundException*/UploadResult uploadFile(MultipartFile file,HttpServletRequest request) throws FileNotFoundException;/*** 下载文件* @param request* @param response* @throws Exception*/void downLoad(HttpServletRequest request, HttpServletResponse response) throws Exception;
}

3、实现类编写

@Service
public class UploadServiceImple implements UploadService {/*** 项目路径*/@Value("${file.upload.path}")private String baseStoragePath;@Overridepublic UploadResult uploadFile(MultipartFile file, HttpServletRequest request) throws FileNotFoundException {if (null == file) {throw new FileNotFoundException("无效的文件");}InputStream inputStream;try {inputStream = file.getInputStream();} catch (IOException e) {throw new FileNotFoundException("无效的文件内容");}String originName = file.getOriginalFilename();String parent = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));File localFolder = new File(baseStoragePath, parent);//根据日期创建文件夹if (!localFolder.exists()) {localFolder.mkdirs();}//后缀不变,文件名称随机生成String fileName = UUID.randomUUID().toString().concat(originName.substring(originName.indexOf(".")));File localFile = new File(localFolder, fileName);OutputStream outputStream = new FileOutputStream(localFile);try {FileCopyUtils.copy(inputStream, outputStream);} catch (IOException e) {e.printStackTrace();throw new FileNotFoundException("文件存储失败……");}UploadResult result = new UploadResult();result.setFileName(originName);result.setFilePath("/" + parent + "/" + fileName);return result;}@Overridepublic void downLoad(HttpServletRequest request, HttpServletResponse response) throws Exception {//项目根路径String property = System.getProperty("user.dir");// ISO-8859-1 ==> UTF-8 进行编码转换String path = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);String bestMatchPattern = (String) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);String filePath = new AntPathMatcher().extractPathWithinPattern(bestMatchPattern, path);InputStream inputStream = null;OutputStream outputStream = null;try {filePath = filePath.replace("..", "");if (filePath.endsWith(",")) {filePath = filePath.substring(0, filePath.length() - 1);}String localPath = property + "/" + baseStoragePath;String downloadFilePath = localPath + File.separator + filePath;File file = new File(downloadFilePath);if (file.exists()) {// 设置强制下载不打开response.setContentType("application/force-download");response.addHeader("Content-Disposition", "attachment;fileName=" + new String(file.getName().getBytes("UTF-8"), "iso-8859-1"));inputStream = new BufferedInputStream(new FileInputStream(file));outputStream = response.getOutputStream();byte[] buf = new byte[1024];int len;while ((len = inputStream.read(buf)) > 0) {outputStream.write(buf, 0, len);}response.flushBuffer();}} catch (Exception e) {} finally {if (inputStream != null) {try {inputStream.close();} catch (IOException e) {e.printStackTrace();}}if (outputStream != null) {try {outputStream.close();} catch (IOException e) {e.printStackTrace();}}}}}

4、上传文件描述类

@Setter
@Getter
public class UploadResult {/*** 文件名称*/private String fileName;/*** 文件路径*/private String filePath;
}

5、开发环境中会在文件根路径生成文件并下载
6、如果将项目打成war包,部署到tomcat中,则需要tomcat中配置文件访问路径,否则报404

  <Host appBase="webapps" autoDeploy="true" name="localhost" unpackWARs="true"><!-- SingleSignOn valve, share authentication between web applicationsDocumentation at: /docs/config/valve.html --><!--<Valve className="org.apache.catalina.authenticator.SingleSignOn" />-->
<--docbase服务器绝对路径,path访问路径 --><Context path="/uploadFile" docBase="/data/tomcat/apache-tomcat-9.0.27/uploadFile" debug="0" reloadable="true"/><!-- Access log processes all example.Documentation at: /docs/config/valve.htmlNote: The pattern used is equivalent to using pattern="common" --><Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs" pattern="%h %l %u %t &quot;%r&quot; %s %b" prefix="localhost_access_log" suffix=".txt"/></Host>

上传文件到服务器并通过浏览器直接下载附件(springboot)相关推荐

  1. 上传文件到服务器并显示,J2EE如何实现Servlet上传文件到服务器并相应显示功能...

    J2EE如何实现Servlet上传文件到服务器并相应显示功能 发布时间:2021-07-10 11:44:54 来源:亿速云 阅读:82 作者:小新 这篇文章将为大家详细讲解有关J2EE如何实现Ser ...

  2. Android上传文件至服务器(转)

    本实例实现每隔5秒上传一次,通过服务器端获取手机上传过来的文件信息并做相应处理:采用Android+Struts2技术. 一.Android端实现文件上传 1).新建一个Android项目命名为and ...

  3. ftp给服务器上传文件,ftp上传文件给服务器

    ftp上传文件给服务器 内容精选 换一换 客户端连接服务端超时,无法连接到服务端.该文档适用于本地主机Windows系统上的FTP服务.服务端防火墙或安全组拦截.检查服务端防火墙设置.关闭防火墙或者添 ...

  4. 个人上传文件进服务器,个人上传文件进服务器

    个人上传文件进服务器 内容精选 换一换 安装传输工具在本地主机和Windows云服务器上分别安装数据传输工具,将文件上传到云服务器.例如QQ.exe.在本地主机和Windows云服务器上分别安装数据传 ...

  5. 服务器如何接收curl上传文件,linux curl上传文件到服务器

    linux curl上传文件到服务器 内容精选 换一换 为了实现通过NAT Server可使用SSH协议跳转到SAP HANA节点的功能,以及SAP HANA节点和NAT Server互相通过SSH协 ...

  6. ios如何上传文件到服务器,ios通过ftp上传文件到服务器

    ios通过ftp上传文件到服务器 内容精选 换一换 华为云帮助中心,为用户提供产品简介.价格说明.购买指南.用户指南.API参考.最佳实践.常见问题.视频帮助等技术文档,帮助您快速上手使用华为云服务. ...

  7. ftp ios 上传文件到服务器上,ios通过ftp上传文件到服务器

    ios通过ftp上传文件到服务器 内容精选 换一换 华为云帮助中心,为用户提供产品简介.价格说明.购买指南.用户指南.API参考.最佳实践.常见问题.视频帮助等技术文档,帮助您快速上手使用华为云服务. ...

  8. C 上传文件到服务器(含接收端源码)

    2019独角兽企业重金招聘Python工程师标准>>> 本文demo下载地址:http://www.wisdomdd.cn/Wisdom/resource/articleDetail ...

  9. android 上传文件到服务器

    1.编写layout.xml <LinearLayout android:layout_width="match_parent"android:layout_height=& ...

最新文章

  1. 为什么「反向传播」一定要在生物学上有对应?
  2. 树莓派模拟量输入范围_使用 RPi.GPIO 模块的输入(Input)功能
  3. To B服务想做移动化?腾讯云案例了解一下
  4. Selenium 控制浏览器
  5. zabbix简单介绍(1)
  6. jsp循环输出表格_「翻译」JS可视化学习之七:Promise、事件循环和异步2
  7. 年薪35万的深度学习工程师,正面临数百万的人才缺口
  8. 基础知识(十)C++常用函数.txt
  9. :hover 鼠标悬浮时(基本导航)
  10. 运用思维导图学习数据分析的五个步骤
  11. python画散点图-python中画散点图
  12. windows 10上fastboot无法识别设备问题
  13. linux 内核 addr2line,linux内核调试技巧之addr2line
  14. 软硬件交互 - 扫码枪
  15. 中国互联网用户各阶级的分析
  16. Android常用应用市场和应用包名
  17. 触控面板 开发_长信科技研发内核不断升级 成触控显示一体化领军企业
  18. ESP32 HttpServer模式下 本地OTA 例程(基于ESP-IDF类似Arduino下OTAWebUpdater例程)
  19. LuoguP1456 - Monkey King| 左倾堆 | 左偏树
  20. 如何发现「将死」的ReLu?可视化工具TensorBoard助你一臂之力

热门文章

  1. MySQL启动报错1067(附排查解决方法)
  2. hihocoder1479
  3. linux设备驱动之I/O通道解析
  4. 视频图像处理——图像比较与分镜头
  5. Nordic 52832 BLE Central Demo 分析
  6. 墨者靶场 初级:Bash漏洞分析溯源
  7. BD Rhapsody单细胞分析系统
  8. 亚洲护照实力进一步加强
  9. html gif素材在哪儿找,不会GIF动图制作?不知道从哪里找动图素材?送你2个网站1个软件...
  10. QT学习之视图框架下的简单的碰撞检测