欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

spring boot 图片上传与显示(二)

程序员文章站 2022-05-17 09:04:16
...

推荐

spring boot 图片上传与显示(二)

spring boot 图片上传与显示(二)
创建个uril包,用于存放工具类,这个方法,便于后期的代码维护。

先在启动类(Application.java)中创建虚拟路径

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/Test/src/main/resources/static/");
    }
}

util包下的uploadutil.java

package com.sdbairui.demo.Util;

import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

public class UploadUtil {
    //源文件名
    private String originalFilename;

    //源文件后缀名
    private String suffix;

    //存入数据库里的tomcat虚拟路径
    private String dbPath;

    //文件大小
    private long size;

    //实际存储路径
    private String realPath;

    /**
     * 文件上传工具类
     * @param attach
     * @param request
     * @param uploader 文件上传者
     * @return
     */
    public boolean doUpload(MultipartFile attach, HttpServletRequest request, String uploader){

        if(!attach.isEmpty()){

            originalFilename = attach.getOriginalFilename();
            System.out.println("==>上传的文件名:"+originalFilename);

            suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            System.out.println("==>上传的文件后缀名:"+suffix);

            size = attach.getSize();
            System.out.println("==>上传文件的大小:"+size);

            String currentFilename = System.currentTimeMillis()+ UUID.randomUUID().toString() + suffix;
            System.out.println("==>存储的上传文件名:"+currentFilename);

            realPath = "D:/Intellij IDEA/IntelliJ IDEA 2020.1/SpringBoot/Test/src/main/resources/static/"+uploader ;
            System.out.println("==>上传文件保存的真实路径:"+realPath);

            File targetFile = new File(realPath, currentFilename);
            if(!targetFile.exists()){
                targetFile.mkdirs();
            }

            try{
                attach.transferTo(targetFile);
            }catch (Exception e){
                e.printStackTrace();
                return false;
            }
            realPath = realPath + "/" + currentFilename;
//            dbPath =  request.getContextPath() + "/" + uploader + "/" + new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + "/" + currentFilename;
            dbPath = "/" + uploader + "/" + currentFilename;
            return true;
        }else{
            return false;
        }
    }
    public String getUploadFile(){
        return dbPath;
    }
}

控制类(Controller)

@RequestMapping(value = "/upload",method = RequestMethod.POST)
@ResponseBody
public String testUpload(@RequestParam("file")MultipartFile file,HttpServletRequest request) {

    UploadUtil uploadUtil = new UploadUtil();
    String fileName = "";
    if (uploadUtil.doUpload(file, request, "uploadImg")) {
        fileName = uploadUtil.getUploadFile();
    } else {
        fileName = "file";
    }

    return fileName;
}

前端界面

上传图片,我用的是JavaScript的Ajax 的方式进行上传的

这个是表单内容
 <div class="int">
        <input type="file" name="sname" id="file"><br> <!-- file书写浏览上传的文件-->
        <!--接受显示上传图片的路径,作用是将图片的路径上传到后台服务器端,来达到上传图片的效果-->
        <input type="text" name="file" id="sfile">
        <!-- 显示上传图片的内容 -->
        <p id="url"><img src="" width="130" height="80"></p>
        <input type="button" value="上传" id="upload">
        <input type="button" value="取消" id="clean"> <br>
    </div>
这个是Ajax代码
$("#upload").click(function () {
            // 获取表单内容
            var form =new FormData();
            // 将表单内容,通过数组记录下来
            form.append("file",document.getElementById("file").files[0]);
            $.ajax({
                url: "/person/upload",
                data: form,
                cache: false,
                async: false,
                type: 'post',
                dataType: 'text',
                processData: false,
                contentType: false,
                success:function (data) {
                    // 成功时,提示的后台JSON数据
                    // alert(JSON.stringify(data));
                    if(data){
                        $("#url img").attr("src","/imctemp-rainy/"+ data);
                        $("#sfile").val("/imctemp-rainy/"+ data);
                        // $("#url img").attr("src","/imctemp-rainy/"+data);
                        // var pic=data
                        // // 将上传图片存入内部磁盘当中
                        //  $("#url img").attr("src",pic);
                        // // 将上传的图片路径保存在id为sfile当中
                        // $("#sfile").val("/imctemp-rainy/"+data.fileName);
                    }
                },
            })
        })
    });

index.html(显示)

<td ><img th:src="@{${person.file}}" height="80" width="130"></td>
相关标签: Springboot框架