Java编程技巧:文件上传、下载、预览

目录

      • 1、上传文件
        • 1.1、代码
        • 1.2、postman测试截图
      • 2、下载resources目录中的模板文件
        • 2.1、项目结构
        • 2.2、代码
        • 2.3、使用场景
      • 3、预览文件
        • 3.1、项目结构
        • 3.2、代码
        • 3.3、使用场景

1、上传文件

1.1、代码
@PostMapping("/uploadFile")
public String uploadFile(MultipartFile file) {System.out.println("文件名称:" + file.getOriginalFilename());return "成功";
}@PostMapping("/uploadFile2")
public String uploadFile2(@RequestParam("file") MultipartFile file
) {System.out.println("文件名称:" + file.getOriginalFilename());return "成功";
}@PostMapping("/uploadFile3")
public String uploadFile3(@RequestPart("file") MultipartFile file
) {System.out.println("文件名称:" + file.getOriginalFilename());return "成功";
}// 发送文件的同时带上参数
@PostMapping("/uploadFile4")
public String uploadFile4(@RequestPart("file") MultipartFile file, // 可以换成“MultipartFile file”或者“@RequestParam("file") MultipartFile file”@RequestParam("id") String id
) {System.out.println("文件名称:" + file.getOriginalFilename());System.out.println("id:" + id);return "成功";
}
1.2、postman测试截图

在这里插入图片描述

2、下载resources目录中的模板文件

2.1、项目结构

假设resources目录下有一个pdf文件:用户数据导入模板.xlsx,然后我们来下载该文件

在这里插入图片描述

2.2、代码
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;
import org.springframework.http.MediaTypeFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;@RestController
public class TestController {@GetMapping("/downloadLocalFile")public void downloadLocalFile(HttpServletResponse response) throws IOException {String fileName = "用户数据导入模板.xlsx";Resource r = new ClassPathResource(fileName);try (FileInputStream fileInputStream = new FileInputStream(r.getFile());ServletOutputStream outputStream = response.getOutputStream();) {response.setContentType("application/force-download");try {fileName = new String(fileName.getBytes("utf-8"), "ISO-8859-1");} catch (UnsupportedEncodingException e) {e.printStackTrace();}response.setHeader("Content-Disposition", "attachment;filename=" + fileName);IOUtils.copyLarge(fileInputStream, outputStream);} catch (Exception e) {e.printStackTrace();}}
}
2.3、使用场景

在这里插入图片描述

3、预览文件

3.1、项目结构

resources下面的文件为例,展示预览文件的代码,这是从本地获取文件,当然也可以通过其他方式获取文件

在这里插入图片描述

3.2、代码
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;
import org.springframework.http.MediaTypeFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;@RestController
public class TestController {@GetMapping("/previewLocalFile")public void previewLocalFile(HttpServletResponse response) throws IOException {String fileName = "SQL必知必会(第5版).pdf";Resource r = new ClassPathResource(fileName);try (FileInputStream fileInputStream = new FileInputStream(r.getFile());ServletOutputStream outputStream = response.getOutputStream();) {// 区别点1:将“response.setContentType("application/force-download");”替换成下面内容response.setContentType(MediaTypeFactory.getMediaType(fileName).orElse(MediaType.APPLICATION_OCTET_STREAM).toString());try {fileName = new String(fileName.getBytes("utf-8"), "ISO-8859-1");} catch (UnsupportedEncodingException e) {e.printStackTrace();}// 区别点2:预览是“filename”,下载是“attachment;filename=”response.setHeader("Content-Disposition", "filename=" + fileName);IOUtils.copyLarge(fileInputStream, outputStream);} catch (Exception e) {e.printStackTrace();}}
}
3.3、使用场景

在网盘软件中预览pdf文件

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/120912.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

WebPack-打包工具

从图中我们可以看出,Webpack 可以将多种静态资源 js、css、less 转换成一个静态文件,减少了页面的请求. 下面举个例子 : main.js 我们只命名导出一个变量 export const name"老六"index.js import { name } from "./tset/…

什么是Promise链(Promise chaining)?它在异步编程中的作用是什么?

聚沙成塔每天进步一点点 ⭐ 专栏简介⭐ 什么是 Promise 链?⭐ 异步编程中的作用⭐ 写在最后 ⭐ 专栏简介 前端入门之旅:探索Web开发的奇妙世界 欢迎来到前端入门之旅!感兴趣的可以订阅本专栏哦!这个专栏是为那些对Web开发感兴趣、…

【PDF】pdf 学习之路

PDF 文件格式解析 https://www.cnblogs.com/theyangfan/p/17074647.html 权威的文档: 推荐第一个连接: PDF Explained (译作《PDF 解析》) | PDF-Explained《PDF 解析》https://zxyle.github.io/PDF-Explained/ https://zxyle…

VBA技术资料MF61:按每行指定字符数自动换行

【分享成果,随喜正能量】人生的旅途,一时的失意,一时的挫折,跌了一跤,不是人生的全部,只是人生的一个逗点,未来的成就、光辉,还有很多的虚线有待你继续去完成。。 我给VBA的定义&am…

【前端】ECMAScript6从入门到进阶

【前端】ECMAScript6从入门到进阶 1.ES6简介及环境搭建 1.1.ECMAScript 6简介 (1)ECMAScript 6是什么 ECMAScript 6.0(以下简称 ES6)是 JavaScript 语言的下一代标准,已经在2015年6月正式发布了。它的目标&#xff…

asp.net core mvc Razor +dapper 增删改查,分页(保姆教程)

说明:本demo使用sqlserver数据库,dapper orm框架 完成一张学生信息表的增删改查,前端部分使用的是Razor视图, Linq分页 HtmlHelper。(代码随便写的,具体可以自己优化) //实现效果如下&#xff0…

macOS 下 Termius 中文显示为乱码

👨🏻‍💻 热爱摄影的程序员 👨🏻‍🎨 喜欢编码的设计师 🧕🏻 擅长设计的剪辑师 🧑🏻‍🏫 一位高冷无情的编码爱好者 大家好,我是 DevO…

Qt 画自定义饼图统计的例子

先给出结果图,这个例子是将各种事件分类然后统计的其比例,然后画饼图显示出来 这个是我仿照官方给的例子,让后自己理解后,修改的,要生成饼图,需要QT的 charts 支持,安装QT 没有选择这个的&#…

Linux系统编程(1)

父子进程通过两个管道进行通信。 伪代码 #include <unistd.h> void client(int, int), server(int, int);int main(int argc, char** argv) {int pipe1[2], pipe2[2];pid_t childpid;Pipe(pipe1);Pipe(pipe2);if ((childpid Fork()) 0) {// childClose(pipe1[1]);Close…

上网Tips: Linux截取动态效果图工具_byzanz

链接1 链接2 安装&#xff1a; sudo apt-get install byzanz 查看指令 说明 byzanz-record --help日常操作 xwininfo点击 待录制窗口 左上角 byzanz-record -x 72 -y 64 -w 1848 -h 893 -d 10 --delay5 -c /home/xixi/myGIF/test.gif小工具 获取鼠标坐标 xdotool getm…

python使用mitmproxy和mitmdump抓包之拦截和修改包(四)

我认为mitmproxy最强大的地方&#xff0c;就是mitmdump可以结合python代码&#xff0c;灵活拦截和处理数据包。 首先&#xff0c;mitmdump的路径如下&#xff1a;&#xff08;使用pip3 install mitmproxy安装的情况&#xff0c;参考我的文章python使用mitmproxy和mitmdump抓包…

Django(21):使用Celery任务框架

目录 Celery介绍Celery安装Celery使用项目文件和配置启动Celery编写任务调用异步任务查看任务执行状态及结果 设置定时和周期性任务配置文件添加任务Django Admin添加周期性任务启动任务调度器beat Flower监控任务执行状态Celery高级用法与注意事项给任务设置最大重试次数不同任…