springboot中的图片上传和下载

springboot中的图片上传和下载

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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.0</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>demo20220615</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo20220615</name>
    <description>demo20220615</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>RELEASE</version>
            <scope>compile</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

application.properties

spring.servlet.multipart.maxFileSize=20MB

上传

upload.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>vivi</title>
</head>
<body>
<h1>hello Vivi</h1>
<form action="/upload" method="post" enctype="multipart/form-data">
  <input type="file" name="file">
  <input type="submit" value="上传">
</form>
</body>
</html>

FileUploadController

package com.example.demo20220615.controller;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

@RestController
public class FileUploadController {
    @PostMapping("upload")
    @ResponseBody
// MultipartFile 变量名要与 form 表单中的的 type="file" name="file" name 属性名一致
    public void upload(MultipartFile file, HttpServletRequest request) throws IOException {
        System.out.println(file.getOriginalFilename()); // 文件名
        System.out.println(file.getContentType()); // 文件类型
        System.out.println(file.getSize()); // 文件大小

        System.out.println(file.getInputStream()); // 获得文件输入流

        // 获得web应用中 files文件夹的绝对路径
        String realPath = System.getProperty("user.dir") + "/src/main/resources/static/upload";

        System.out.println(realPath);
        File newFile = new File(realPath);
        // 如果文件夹不存在、则新建
        if (!newFile.exists()) newFile.mkdirs();

        // 上传
        file.transferTo(new File(newFile, file.getOriginalFilename()));
    }
}

下载

download.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>文件下载</h1>
<a href="/download?fileName=1.jpg">1.jpg</a>

</body>
</html>

注意:上面的地址是写死的,图片名称根据自己的来写

FileDownloadController

package com.example.demo20220615.controller;

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.File;
import java.io.FileInputStream;
import java.io.IOException;

@RestController
public class FileDownloadController {

    @GetMapping("download")
    public void download(String fileName, HttpServletResponse response) throws IOException {
        // 获得待下载文件所在文件夹的绝对路径
        String realPath = System.getProperty("user.dir") + "/src/main/resources/static/upload";
        System.out.println(realPath);
        // 获得文件输入流
        FileInputStream inputStream = new FileInputStream(new File(realPath, fileName));
        // 设置响应头、以附件形式打开文件
        response.setHeader("content-disposition", "attachment; fileName=" + fileName);
        ServletOutputStream outputStream = response.getOutputStream();
        int len = 0;
        byte[] data = new byte[1024];
        while ((len = inputStream.read(data)) != -1) {
            outputStream.write(data, 0, len);
        }
        outputStream.close();
        inputStream.close();
    }

}

目录结构
在这里插入图片描述

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
A:Spring Boot可以很容易地实现图片上传下载功能。下面是一个简单的示例代码,演示了如何处理图像上传和下载。 1. 图片上传功能 创建一个Spring Boot Controller类,处理图像上传请求: ``` @RestController @RequestMapping("/api/image") public class ImageController { @PostMapping("/upload") public String uploadImage(@RequestParam("file") MultipartFile file) { try { // 保存图片到本地磁盘或云存储 byte[] bytes = file.getBytes(); // ...保存图片代码... return "上传成功!"; } catch (IOException e) { e.printStackTrace(); return "上传失败!"; } } } ``` 2. 图片下载功能 同样创建一个Spring Boot Controller类,处理图像下载请求: ``` @RestController @RequestMapping("/api/image") public class ImageController { @GetMapping("/download") public ResponseEntity<byte[]> downloadImage() { try { // 获取要下载图片文件 String fileName = "test.jpg"; File file = new File(fileName); // 将图片文件转换为字节数组 FileInputStream fis = new FileInputStream(file); byte[] bytes = new byte[fis.available()]; fis.read(bytes); fis.close(); // 设置HTTP响应头,表明响应类型为图片 HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.IMAGE_JPEG); headers.setContentDisposition( ContentDisposition.builder("attachment") .filename(fileName) .build()); // 返回图片字节数组 return new ResponseEntity<>(bytes, headers, HttpStatus.OK); } catch (IOException e) { e.printStackTrace(); return null; } } } ``` 以上是基本的示例代码,您可以根据需求进行更改和优化。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值