springboot图片上传与浏览器展示

本文将介绍如何在SpringBoot应用中实现图片上传功能,并详细讲解如何配置及展示上传后的图片,以便用户在浏览器中查看。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com.demo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @author admin
 */
@RestController
public class UploadController {
    /**上传文件
     * @param username
     * @param inputfile. MultipartFile变量的名字需要与上传文件时的name保持一致 .<input type="file" name="inputfile">
     * @return
     * @throws IOException
     */

    @PostMapping("/uploadfile")
    public String uploadFile(String username, MultipartFile inputfile) throws IOException {
        String originalFilename = inputfile.getOriginalFilename();

        String sub = originalFilename.split("\\.")[1];
        String subname;
        if (!username.equals("")) {
            subname = username.concat("." + sub);
        } else {
            subname = originalFilename;
        }
        System.out.println(subname);
        System.out.println(originalFilename);
        System.out.println(inputfile.getName());
        inputfile.transferTo(new File("E:/文件/" + subname));

        return "上传成功";
    }

    @Autowired
    private ResourceLoader resourceLoader;
    // 浏览器显示图片
    @GetMapping("/getImg/{imgname:.+}")
    public ResponseEntity getImg(@PathVariable String imgname) {
        System.out.println(imgname);
        Path path = Paths.get("F:\\文件", imgname);
        System.out.println(path);
        Resource resource = resourceLoader.getResource("file:" + path.toString());
        //默认springb 2.x,ResponseEntity.ok(resource) 在浏览器显示为流文件,添加contentType返回指定类型. 1.x直接返回即可

        return ResponseEntity.ok().contentType(MediaType.IMAGE_JPEG).body(resource);
    }
}

上传页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>图片上传</title>
</head>
<body>
  <form action="/uploadfile" method="post" enctype="multipart/form-data">
      <span>文件名<input type="text" name="username" ></span>
      <input type="file" name="inputfile">
      <input type="submit" value="上传">
  </form>
</body>
</html>
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值