springboot 图片上传与显示功能的实现(一)

springboot 图片上传与显示功能的实现

先在pom.xml中添加所需的jar包依赖

<!-- java 与json 数据转换 -->
<dependency>
    <groupId>net.sf.json-lib</groupId>
    <artifactId>json-lib</artifactId>
    <version>2.2.3</version>
    <classifier>jdk15</classifier>
</dependency>

- 在修改一下启动类(Application)中的设置

为什么继承WebMvcConfigurer接口呢?

  • 原因是这个接口中有addResourceHandlers方法,此方法是为了自定义静态资源映射路径,也就是说:图片将图片上传到内部磁盘当中,addResourceHandler这个方法通俗一点就是说将内部路径重命名在外部显示。
package com.sdbairui.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@SpringBootApplication
public class DemoApplication implements WebMvcConfigurer {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

//    自定义静态资源映射目录
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry){
        /*
            addResoureHandler:指的是对外暴露的访问路径
            addResourceLocations:指的是内部文件放置的目录
        */
        registry.addResourceHandler("/imctemp-rainy/**").addResourceLocations("file:D:/Intellij IDEA/IntelliJ IDEA 2020.1/SpringBoot/Student/src/main/resources/static/uploadimage/");
    }
}

在数据库当中添加file列,我用的是MySQL数据库
在这里插入图片描述
然后在属性Entiy包中的属性类的Student添加SetterGetter 方法

private String file;

public String getFile() {
    return file;
}

public void setFile(String file) {
    this.file = file;
}

在后端Controller控制类中进行后台的编写

  public static void uploadFile(byte[] file,String filePath,String fileName)throws Exception{
        File targetFile=new File(filePath);
     /* !targetFile.exists():是否存在指定条件的记录*/
        if(!targetFile.exists()){
//         targetFile.mkdirs()创建新的目录 
            targetFile.mkdirs();
        }
        FileOutputStream fileOutputStream=new FileOutputStream(filePath+fileName);
        fileOutputStream.write(file);
        fileOutputStream.flush();
        fileOutputStream.close();
    }
    @RequestMapping(value = "/upload",method = RequestMethod.POST)
    @ResponseBody
//    JSONObject可以很方便的转换成字符串,也可以很方便的把其他对象转换成JSONObject对象。
    public JSONObject uploadImg(@RequestParam("file")MultipartFile file){
        /*获得上传图片并重命名成随机名字
        System.currentTimeMillis():获得系统的时间,单位为毫秒
        file.getOriginalFilename():是得到上传时的文件名。*/
        String fileName=System.currentTimeMillis()+file.getOriginalFilename();
//        声明内部路径
        String filePath="D:/Intellij IDEA/IntelliJ IDEA 2020.1/SpringBoot/Student/src/main/resources/static/uploadimage/";
        JSONObject jo = new JSONObject();
//        判断上传的文件是否为空,当为空时,给JSONObject传值
        if(file.isEmpty()){
            jo.put("success",0);
            jo.put("fileName","");
        }
//        当上传文件不为空时,调用upload方法,为JSONObject的对象传值
        try{
            uploadFile(file.getBytes(),filePath,fileName);
            jo.put("success",1);
            jo.put("fileName",fileName);
            jo.put("xfilename","/imctemp-rainy/"+fileName);
        }catch (Exception e){
            e.printStackTrace();
        }
        return jo;
    }
}

在前端,编写web上传界面,在此我用是jQuery代码和Ajax

<tr>
            <td>图片地址:</td>
            <td>
                <input type="file" name="sname" id="file"><br> <!-- file书写浏览上传的文件-->
                <!--接受显示上传图片的路径,作用是将图片的路径上传到后台服务器端,来达到上传图片的效果-->
                <input type="text" name="file" id="sfile">
                <!-- 显示上传图片的内容 -->
                <p id="url"><img src="#" width="100" height="100"></p>
                <input type="button" value="上传" id="upload">
                <input type="button" value="取消" id="clean"> <br>
                <input type="submit" value="提交">
            </td>
        </tr>
    </form>
</table>
</center>
<script  src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
    $(function(){
        $("#upload").click(function () {
            // 获取表单内容
            var form =new FormData();
            // 将表单内容,通过数组记录下来
            form.append("file",document.getElementById("file").files[0]);
            $.ajax({
                url: "/student/upload",
                data: form,
                cache: false,
                async: false,
                type: 'post',
                dataType: 'json',
                processData: false,
                contentType: false,
                success:function (data) {
                    // 成功时,提示的后台JSON数据
                    alert(JSON.stringify(data));
                    if(data){
                        var pic=data.xfilename;
                        // 将上传图片存入内部磁盘当中
                        $("#url img").attr("src",pic);
                        // 将上传的图片路径保存在id为sfile当中
                        $("#sfile").val("/imctemp-rainy/"+data.fileName);
                    }else {
                     alert("error");
                    }
                },
                error:function (er) {

                }
            })
        })
    })
</script>

通过提交按钮,提交到后台的Controller控制类中的doAdd方法中,把上传的图片路径保存在数据库当中

@RequestMapping("/doAdd")
public String doAdd(HttpServletRequest request) throws Exception {

    String file=request.getParameter("file");
    Student student=new Student();
    student.setFile(file);
   
    serviceStudent.doCreate(student);
    return "redirect:/student/findPage";
}

最后就是成功之后图片在前端的web页面中的显示功能

<td><img th:src="@{${student.file}}" height="100" width="100"></td>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

平平常常一般牛

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值