SpringBoot文件上传和下载

来源:互联网 发布:java随机生成小写字母 编辑:程序博客网 时间:2024/05/17 06:07

Controller:

@RestController@Api(value = "文件上传下载相关接口")@RequestMapping(value = "/file", produces = "application/json;charset=utf-8")public class FileController {    private static final Logger log = LoggerFactory.getLogger(FileController.class);    @ApiOperation("单文件上传")    @PostMapping    public JsonResult<Void> fileUpload(MultipartFile file) throws IOException {        if (null == file) {            log.error("上传文件不能为空");            return new JsonResult<>("4", "上传文件不能为空!");        }        String fileName = file.getOriginalFilename();        byte[] bytes = file.getBytes();        log.info("开始上传文件【{}】...", fileName);        FileUtils.writeByteArrayToFile(new File("d:/" + fileName), bytes);        log.info("文件【{}】上传成功...", fileName);        return new JsonResult<>();    }    @ApiOperation("多文件上传")    @PostMapping("/batch")    public JsonResult<Void> batchFileUpload(HttpServletRequest request) throws IOException {        List<MultipartFile> fileList = ((MultipartHttpServletRequest) request).getFiles("file");        for (int i = 0; i < fileList.size(); i++) {            MultipartFile file = fileList.get(i);            byte[] bytes = file.getBytes();            log.info("开始上传文件【{}】...", i);            FileUtils.writeByteArrayToFile(new File("d:/temp" + file.getOriginalFilename()), bytes);            log.info("文件【{}】上传成功...", i);        }        return new JsonResult<>();    }    @ApiOperation("文件下载")    @GetMapping("/download")    public JsonResult<Void> download(HttpServletResponse response) throws UnsupportedEncodingException {        String fileName = "干净桌面.jpg";        // 设置强制下载不打开        response.setContentType("application/force-download");        response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("utf-8"),"ISO-8859-1"));//        byte[] buff = new byte[1024];        BufferedInputStream bis = null;        try {            ServletOutputStream outputStream = response.getOutputStream();            byte[] buff = FileUtils.readFileToByteArray(new File("C:\\Users\\Administrator\\Pictures\\电脑桌面\\" + fileName));            outputStream.write(buff);        } catch (IOException e) {            e.printStackTrace();        }        return new JsonResult<>();    }}

Freemarker:

<!doctype html><html lang="zh-cn"><head>    <meta charset="UTF-8">    <meta name="viewport"          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">    <meta http-equiv="X-UA-Compatible" content="ie=edge">    <title>File</title></head><body>    <p>Get your greeting <a href="/greeting">here</a></p>    <form action="/upload" method="POST" enctype="multipart/form-data">        文件:<input type="file" name="test"/>        <input type="submit"/>    </form>    <a href="/file/download">下载test</a>    <p>多文件上传</p>    <form method="POST" enctype="multipart/form-data" action="/file/batch">        <p>文件1:<input type="file" name="file"/></p>        <p>文件2:<input type="file" name="file"/></p>        <p><input type="submit" value="上传"/></p>    </form></body></html>

配置文件application.yml:

#设置激活的环境 devspring:  profiles:      active: dev#------------------------------------------------------------------------------------------  datasource:      name: test      url: jdbc:mysql://127.0.0.1:3306/mytest?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull      username: root      password: 123456      # 使用druid数据源      type: com.alibaba.druid.pool.DruidDataSource      driver-class-name: com.mysql.jdbc.Driver      druid:        initial-size: 1        min-idle: 20        max-active: 300        test-on-borrow: true#freemarker  freemarker:    template-loader-path: classpath:/templates    #设置禁用模板引擎缓存    cache: false    settings:      template_update_delay: 0#静态文件  mvc:    static-path-pattern: /static/**#文件上传设置  http:    multipart:      max-file-size: 100MB      max-request-size: 100MB#devtools  devtools:    restart:      enabled: true#pagehelper分页插件pagehelper:    helperDialect: mysql    reasonable: true    supportMethodsArguments: true    params: count=countSql#jar外部配置logback.xmllogging:  config: logback.xmlmybatis:  type-aliases-package: com.iflytek.icourt.model  mapper-locations: classpath:mapping/*.xml

pom.xml文件:

<?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">    <modelVersion>4.0.0</modelVersion>    <groupId>com.iflytek</groupId>    <artifactId>sm-admin</artifactId>    <version>0.0.1-SNAPSHOT</version>    <packaging>jar</packaging>    <name>sm-admin</name>    <description>Spring Boot Mybatis integration</description>    <parent>        <groupId>org.springframework.boot</groupId>        <artifactId>spring-boot-starter-parent</artifactId>        <version>1.5.9.RELEASE</version>        <relativePath/> <!-- lookup parent from repository -->    </parent>    <properties>        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>        <java.version>1.8</java.version>    </properties>    <dependencies>        <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-jdbc</artifactId>        </dependency>        <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-web</artifactId>        </dependency>        <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-freemarker</artifactId>        </dependency>        <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-devtools</artifactId>            <optional>true</optional>        </dependency>        <dependency>            <groupId>mysql</groupId>            <artifactId>mysql-connector-java</artifactId>            <version>5.1.35</version>        </dependency>        <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-test</artifactId>            <scope>test</scope>        </dependency>        <!--springBoot MyBatis 及 插件依赖 -->        <dependency>            <groupId>org.mybatis.spring.boot</groupId>            <artifactId>mybatis-spring-boot-starter</artifactId>            <version>1.3.1</version>        </dependency>        <!--阿里 Druid Spring Boot Starter依赖 -->        <dependency>            <groupId>com.alibaba</groupId>            <artifactId>druid-spring-boot-starter</artifactId>            <version>1.1.4</version>        </dependency>        <!-- 公共MyBatis mapper -->        <dependency>            <groupId>tk.mybatis</groupId>            <artifactId>mapper-spring-boot-starter</artifactId>            <version>1.1.4</version>        </dependency>        <dependency>            <groupId>com.github.pagehelper</groupId>            <artifactId>pagehelper-spring-boot-starter</artifactId>            <version>1.2.1</version>        </dependency>        <!--阿里 FastJson依赖 -->        <dependency>            <groupId>com.alibaba</groupId>            <artifactId>fastjson</artifactId>            <version>1.2.38</version>        </dependency>        <!--阿里 Druid Spring Boot Starter依赖 -->        <dependency>            <groupId>com.alibaba</groupId>            <artifactId>druid-spring-boot-starter</artifactId>            <version>1.1.4</version>        </dependency>        <!-- Swagger相关 start -->        <dependency>            <groupId>io.springfox</groupId>            <artifactId>springfox-swagger-ui</artifactId>            <version>2.2.2</version>        </dependency>        <dependency>            <groupId>io.springfox</groupId>            <artifactId>springfox-swagger2</artifactId>            <version>2.2.2</version>        </dependency>        <!-- 自定义配置 -->        <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-configuration-processor</artifactId>            <optional>true</optional>        </dependency>        <!-- commons-io -->        <dependency>            <groupId>commons-io</groupId>            <artifactId>commons-io</artifactId>            <version>2.5</version>        </dependency>    </dependencies>    <build>        <plugins>            <plugin>                <groupId>org.springframework.boot</groupId>                <artifactId>spring-boot-maven-plugin</artifactId>            </plugin>            <!-- mybatis generator 自动生成代码插件 -->            <plugin>                <groupId>org.mybatis.generator</groupId>                <artifactId>mybatis-generator-maven-plugin</artifactId>                <version>1.3.2</version>                <configuration>                    <configurationFile>${basedir}/src/main/resources/generator/generatorConfig.xml</configurationFile>                    <overwrite>true</overwrite>                    <verbose>true</verbose>                </configuration>            </plugin>        </plugins>    </build></project>
阅读全文
'); })();
0 0
原创粉丝点击
热门IT博客
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 临震预报 小时预报 tqyb 预提费用 预提所得税 企业所得税预提费用 预提费用是什么科目 预提费用 所得税调整 预提费用的会计分录 预提费用科目取消了吗 预提本月银行借款利息3000元 预提费用属于什么科目 出乎预料 预料 预料的英文 预料英文 预料的近义词 预料的近义词是什么 你无法预料的分手 预期 预期收益率 预期收益 预期寿命 预期焦虑症 预期焦虑 预期是什么意思 预期收益率计算公式 预期什么意思 2019人均预期寿命 iphone11预购优于预期 预案 安全预案 反恐预案 应急预案包括哪些内容 应急预案管理办法 应急救援预案 应急预案演练 火灾应急预案 应急预案怎么写 护理应急预案 应急预案模板