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

springboot + vue上传图片在服务器并实现在线预览

程序员文章站 2022-06-24 12:34:55
后台需要配置一个upload工具类public class UploadUtils {//静态资源路径public final static String IMG_PATH_PREFIX = "statics/upload/imgs";public static File getImgDirFile(){//dome是项目名String fileDirPath = new String("dome/src/main/resources/" + IMG_PATH_PREFI....
  1. 后台需要配置一个upload工具类

public class UploadUtils {
		//静态资源路径
	public final static String IMG_PATH_PREFIX = "statics/upload/imgs";

	public static File getImgDirFile(){
		//dome是项目名
		String fileDirPath = new String("dome/src/main/resources/" + IMG_PATH_PREFIX);

		File fileDir = new File(fileDirPath);
		if(!fileDir.exists()){
			
			fileDir.mkdirs();
		}
		return fileDir;
	}

这里是我们的项目结构
springboot + vue上传图片在服务器并实现在线预览

  1. 然后我们在写一个Controller
	@ResponseBody
    @RequestMapping("/upload")
    public R upload(@RequestParam("file")MultipartFile imgFile, HttpServletRequest request, HttpSession session){
        if (imgFile.isEmpty()) {
            return R.error("上传失败,请选择文件");
        }

        // 生成唯一文件名
        String uuid = UUID.randomUUID().toString().trim();
        String filename = imgFile.getOriginalFilename();
        int index=filename.indexOf(".");
        String fileNames=uuid+filename.substring(index);

        // 调用UploadUtils工具类将图片存放到服务器上
        File fileDir = UploadUtils.getImgDirFile();

        try {
            // 构建真实的文件路径
            File newFile = new File(fileDir.getAbsolutePath() + File.separator + fileNames);
            System.out.println(newFile.getAbsolutePath());

            imgFile.transferTo(newFile);

        } catch (IOException e) {
            e.printStackTrace();
        }
        //返回图片名称
        return R.ok().put("fileName",fileNames);
    }
  1. js 我用的是layui 的文件上传去做的,这里看个人使用
  var license = upload.render({
        elem: '#btn_license'
        ,url: baseURL+'sys/upload'
        ,accept: 'license'
        ,method: 'get'
        ,exts: "jpg|png|gif|bmp|jpeg|pdf"

        ,choose: function(){

        }
        ,before: function(obj){
            //预读本地文件示例,不支持ie8
            obj.preview(function(index, file, result){
               $('#license1').attr('src', result); //图片链接(base64)
            });
        }
        ,done: function(res){

            //如果上传失败
            if(res.code > 0){
                return layer.msg('上传失败');
            }
            //上传成功
           // $(" #license ").val(res.fileName);
            console.log(res.fileName);

        }
        ,error: function() {
            this.item.html('重选上传');

            //演示失败状态,并实现重传
            var demoText = $('#license_msg');
            demoText.html('<span style="color: #FF5722;">上传失败</span> ' +
                '<a class="layui-btn layui-btn-mini demo-reload">重试</a>');
            demoText.find('.demo-reload').on('click', function () {
                license.upload();
            });

        }
    });

4.前端vue

  <div class="layui-upload layui-input-inline">
        <button type="button" class="layui-btn" id="btn_license" name="license">上传图片</button>

        <div class="layui-upload-list">
        //这个是为了在线预览,如果不需要可以去除
            <img class="layui-upload-img" onclick="previewImg(this)" name="license" v-model="t04Vehicle.license"  src="" id="license1" />
             <input type="hidden" class="form-control"   id="license" />
            <p id="license_msg"></p>
        </div>
    </div>

5.在线预览功能

//弹窗
function previewImg(obj) {
	//这里直接将项目的路径给拼接上去
    var src = "/dome/statics/upload/imgs/"+$("#"+obj.name).val();
    console.log(src);
    var imgHtml = "<img src=" + src + "/>";
  layer.open({
        type: 1,
        shade: false,
        title: false, 
        area:['800px','800px'],
        content: imgHtml, 
        cancel: function () {
        }
    });
}

6.在线预览我们还需要配置热部署,不然我们在预览图片的时候是无法显示出来的,热部署配置可以自行在网上查找,除了热部署以外我们还需要配置一个Config,如果不配置的话就需要自己手动刷新逞能显示出来

@Configuration
public class UploadConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {

        File file = null;
        try {
            file = new File("");
            String filePath = file.getCanonicalPath();
			//获取项目存放路径
            System.out.println("filePath:"+filePath);
            registry.addResourceHandler("/statics/upload/**").addResourceLocations("file:"+filePath+"/dome/src/main/resources/statics/upload/imgs");

        } catch (Exception e) {

        }
    }

}

本文地址:https://blog.csdn.net/qq_39287951/article/details/107489921