springboot实现简单的图片上传

图片上传在项目中是经常用到的,做一个小的demo方便以后自己复习

这里用springboot的项目项目进行演示

目录结构

在这里插入图片描述

1、添加依赖

       <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

2、添加html

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Insert title here</title>
</head>
<body>
<h1>文件上传入门案例</h1>
<form action="http://localhost:8091/file" method="post"
      enctype="multipart/form-data">

    文件名称:<input name="fileImage" type="file"/><br>
    <input type="submit" value="提交"/>
</form>
</body>


3、编辑首页跳转的controller

package com.study.fileupload.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class IndexController {

    @RequestMapping("/index")
    public String index() {
        return "index";
    }
}

4、文件跳转的url

package com.study.fileupload.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
public class FileController {
    // http://localhost:8091/file
    @RequestMapping("/file")
    public String fileUpload(MultipartFile fileImage) throws IOException {

        System.out.println(fileImage.getOriginalFilename());

        final String imagePathRoot = "E:\\图片\\test-image\\";
        File file = new File(imagePathRoot);

        if (!file.exists()) {
            file.mkdirs();
        }

        String fileName = fileImage.getOriginalFilename();
        String fileType = fileName.substring(fileName.lastIndexOf("."));
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String imageFilePath = imagePathRoot + uuid + fileType;
        fileImage.transferTo(new File(imageFilePath));
        return "upload ok";
    }
}

5、测试代码效果

在这里插入图片描述

5.1、http://localhost:8091/

5.2、选择一个本地图片

5.3、然后提交

5.4、查看文件是否上传成功

在这里插入图片描述

只是简答的演示,实际根据自己的业务场景怎加逻辑判断。

  • 2
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值