SpringBoot+vue多图片上传(url保存到数据库)和回显

application.properties里面写路径
absoluteImgPath = E://Pictures/img/
sonImgPath = img/
service层
@Value("${absoluteImgPath}")
    String absoluteImgPath;
    @Value("${sonImgPath}")
    String sonImgPath;
    public Map<String, String> uploadImg(MultipartFile[] file, FeedBack feedBack) {
        Map<String,String> map = new HashMap<>();
        String path="";
        for (int i = 0; i < file.length; i++) {
                if (file[i].isEmpty()) {
                    map.put("code", "500");
                    map.put("msg", "图片不能为空");
                    System.out.println("图片不能为空");
                    return map;
                }

                String originalFilename = file[i].getOriginalFilename();
                //随机生成文件名
                String fileName = RandomUtils.random() + originalFilename;
                File dest = new File(absoluteImgPath + fileName);
                if (!dest.getParentFile().exists()) {
                    dest.getParentFile().mkdirs();
                }
                String feedPicture = sonImgPath + fileName;
                try {
                    file[i].transferTo(dest);
                    path+=feedPicture+",";
                } catch (Exception e) {
                    map.put("ERROR", e.getMessage());
                    return  map;
                }
            }

        try {
            feedBack.setFeedPicture(path);
            feedBackRepository.save(feedBack);
            map.put("OK", "200");
            return map;
        }
        catch (Exception e){
            map.put("ERROR",  e.getMessage());
            return map;
        }
    }
Controller层
@PostMapping(value = "/uploadImg")
public Map uploadImg(@RequestParam(value = "file",required = false) MultipartFile[] file, FeedBack feedBack){
    feedBack.setFeedStateTime(new Date());
    feedBack.setFeedTime(new Date());
    return feedBackService.uploadImg(file,feedBack);
}
RandomUtils工具类
public class RandomUtils {
    private static boolean IS_THREADLOCALRANDOM_AVAILABLE = false;
    private static Random random;
    private static final long   leastSigBits;
    private static final ReentrantLock lock = new ReentrantLock();
    private static long lastTime;

    static {
        try {
            IS_THREADLOCALRANDOM_AVAILABLE = null != RandomUtils.class.getClassLoader().loadClass(
                    "java.util.concurrent.ThreadLocalRandom"
            );
        } catch(ClassNotFoundException e) {
        }

        byte[] seed = new SecureRandom().generateSeed(8);
        leastSigBits = new BigInteger(seed).longValue();
        if(!IS_THREADLOCALRANDOM_AVAILABLE) {
            random = new Random(leastSigBits);
        }
    }
    /**
     * Create a new random UUID.
     *
     * @return the new UUID
     */
    public static UUID random() {
        byte[] randomBytes = new byte[16];
        if(IS_THREADLOCALRANDOM_AVAILABLE) {
            java.util.concurrent.ThreadLocalRandom.current().nextBytes(randomBytes);
        } else {
            random.nextBytes(randomBytes);
        }

        long mostSigBits = 0;
        for(int i = 0; i < 8; i++) {
            mostSigBits = (mostSigBits << 8) | (randomBytes[i] & 0xff);
        }
        long leastSigBits = 0;
        for(int i = 8; i < 16; i++) {
            leastSigBits = (leastSigBits << 8) | (randomBytes[i] & 0xff);
        }

        return new UUID(mostSigBits, leastSigBits);
    }

    /**
     * Create a new time-based UUID.
     *
     * @return the new UUID
     */
    public static UUID create() {
        long timeMillis = (System.currentTimeMillis() * 10000) + 0x01B21DD213814000L;

        lock.lock();
        try {
            if(timeMillis > lastTime) {
                lastTime = timeMillis;
            } else {
                timeMillis = ++lastTime;
            }
        } finally {
            lock.unlock();
        }

        // time low
        long mostSigBits = timeMillis << 32;

        // time mid
        mostSigBits |= (timeMillis & 0xFFFF00000000L) >> 16;

        // time hi and version
        mostSigBits |= 0x1000 | ((timeMillis >> 48) & 0x0FFF); // version 1

        return new UUID(mostSigBits, leastSigBits);
    }

}
WebMvcConfig工具类
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Value("${absoluteImgPath}")
    String absoluteImgPath;

    @Value("${sonImgPath}")
    String sonImgPath;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/web/images/");
        registry.addResourceHandler(sonImgPath + "**").addResourceLocations("file:"+absoluteImgPath);
    }
}
前端页面,使用vant的uploader图片上传
<p style="clear:both;text-align: left;margin:0px 0px 0px 10px ;color: #999999;padding: 0;">图片信息:(最多10张)</p>

    <van-uploader
      v-model="imgList"
      multiple
      :max-count="10"
      :before-read="asyncBeforeRead"
      :after-read="afterRead"
      :preview-size="60"
    style="margin:5px 0px 0px 10px"
    />
// 图片上传
            let param = new FormData();
            for(let i=0;i<imgList.length;i++) {
              let file = imgList[i].file;
              param.append('file', file);
            }
            param.append('feedPicture', this.feedPicture);
            param.append('feedProblem', this.description);
            param.append('feedDescription', this.problem);
            param.append('feedState', this.feedState);

            // param.append('file', file);
              let config = {
                headers: {'Content-Type': 'multipart/form-data'}
              }; //添加请求头
              this.$http.post('feedBack/uploadImg', param, config)
                .then(response => {
                  console.log(response);
                });

图片上传后,多个url用逗号隔开
在这里插入图片描述

图片回显,我的图片在另一个页面,使用vant进行回显和预览
<van-image
                width="100"
                height="100"
                @click="getPic(index)"
                :src="item"
              >
                <template v-slot:error>无图片</template>
              </van-image>

之后循环从数据库读取图片的url就ok

你可能感兴趣的:(SpringBoot+vue多图片上传(url保存到数据库)和回显)