spring boot图片上传和下载

12 篇文章 0 订阅
7 篇文章 0 订阅

图片上传流程步骤

  1. 前端传送图片(base64)到服务器
  2. 服务器将base64转换为byte []
  3. 服务器根据存储路径生成文件,然后以流的方式写入byte[]
  4. 前端请求图片
  5. 服务器根据路径读取文件,以流的方式返回

前端上传图片

<input
   type="file"
    class="img-upload"
    @change="uploadChange"
    accept="image/*"
/>
uploadChange(el) {
	let that = this;
    if (
        el &&
        el.target &&
        el.target.files &&
        el.target.files.length > 0
    ) {
        const files = el.target.files[0];
        const reader = new FileReader();
        reader.readAsDataURL(files);
        reader.onload = function () {
            that.base64src = this.result; // 图片的base64编码
            ...// 发送http请求
        };
    }
}

服务器保存图片

// application-dev.yml
var:
  uploadFileSavePath: D:\company\static
	// 文件名:FileUtil
	/**
     * yml中的变量,图片存储地址 
     */
    @Value("${var.uploadFileSavePath}")
    public String filePath;

    public Boolean saveFile(String fileName, String base64src) {
        String base64 = base64src.split(",")[1];//通过base64来转化图片,去掉图片头(data:image/jpg;base64,)
        BASE64Decoder decoder = new BASE64Decoder();
        byte[] bytes = null;
        try {
            bytes = decoder.decodeBuffer(base64); // base64 -> byte[]
        }catch (IOException e) {
            return false;
        }
        if(bytes != null) {
            Boolean tag = writeFile(filePath,fileName,bytes);
            if(!tag) {
                return false;
            }
        }
        return true;
    }
	// 文件名:FileUtil
    private Boolean writeFile(String filePath, String fileName, byte[] bytes) {
        Boolean flag = false;
		
        new File(filePath).mkdirs(); // 先创建父目录
        File file = new File(filePath , fileName);
        try {
            FileOutputStream out = new FileOutputStream(file);
            out.write(bytes, 0, bytes.length);
            out.flush();
            out.close();
            flag = true;
        } catch (Exception e) {
            System.out.println(e);
        }
        return flag;
    }

BUG: 文件拒绝访问

创建文件时,必须先创建父目录,再用双参方式初始化file对象,不要使用下面的方式

        File file1 = new File(filePath + File.separator + fileName);
        file1.mkdirs();

服务器返回图片请求

    @Autowired
    private FileUtil fileUtil;

    @GetMapping(value = "/images/{name}",produces = MediaType.IMAGE_JPEG_VALUE)
    @ResponseBody
    public BufferedImage getImage(@PathVariable(name = "name") String fileName) throws IOException {
        File file = new File(fileUtil.filePath,fileName);

        ImageIcon src = new ImageIcon(file.getAbsolutePath());
        // 去除红色png背景
        BufferedImage bufferedImage = new BufferedImage(src.getIconWidth(),
                src.getIconHeight(), BufferedImage.TYPE_INT_RGB);
        Graphics g = bufferedImage.createGraphics();
        g.setColor(Color.white);
        g.fillRect(0, 0, src.getIconWidth(), src.getIconHeight());
        g.drawImage(src.getImage(), 0, 0, null);
        g.dispose();
        ImageIO.write(bufferedImage, "jpg", file);

        return bufferedImage;
    }

BUG: preset Content-Type ‘null’

加一个图片转换器,即可解决

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(new BufferedImageHttpMessageConverter());
    }
}

BUG: 图片背景红色

解决方法代码中已写

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot中实现图片上传到服务器可以通过以下步骤完成: 1. 添加依赖:在pom.xml文件中添加以下依赖,以支持文件上传功能: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.4</version> </dependency> ``` 2. 配置文件上传路径:在application.properties或application.yml文件中配置上传文件的保存路径。例如: ```yaml spring: servlet: multipart: enabled: true location: /path/to/save/files ``` 3. 创建文件上传接口:创建一个Controller类,用于处理文件上传的请求。示例代码如下: ```java import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import java.io.File; import java.io.IOException; @RestController public class FileUploadController { @Value("${spring.servlet.multipart.location}") private String uploadDir; @PostMapping("/upload") public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) { try { String fileName = file.getOriginalFilename(); String filePath = uploadDir + File.separator + fileName; file.transferTo(new File(filePath)); return ResponseEntity.ok("File uploaded successfully!"); } catch (IOException e) { return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to upload file!"); } } } ``` 4. 启动应用程序:运行Spring Boot应用程序并访问`http://localhost:8080/upload`,选择要上传的图片文件,然后点击上传按钮即可将图片上传到服务器指定的路径。 请注意,上述示例中的路径`/path/to/save/files`需要根据实际情况进行更改,并确保你有权限在该路径下创建文件。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值