springboot上传图片并回显,将url存入数据库

 第一步,在webmvcconfig下配置虚拟路径映射,一般来说我们存照片的地址就在主机上创建一个文件夹,也就是file:后边的uploadPathImg,但是我们不能直接访问物理路径的图片,因此我们要配置虚拟路径的映射,前面的/uploadImg/**就是说http://ip地址:+端口号+/uploadImg/**就可以访问到图片了,这里我的uploadPathImg通过@value注解去到yml中找到对应的配置属性值,我们通过yml去配置该值后期便于修改

第二步,配置yaml

virtualImgUrl: http://localhost:9060/HeartKnow/uploadImg/
uploadPathImg: E:/picture/    #本地路径

 上面的virtualImgUrl为存入数据库url的前缀,上传图片之后可以通过该url进行回显

第三步,fileupload工具类的编写

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
@Component
public class FileUpload {
    @Value("${uploadPathImg}")
    private String uploadPathImg;
    @Value("${virtualImgUrl}")
    private String virtualImgUrl;
    public String uploadImg(MultipartFile file){
                String fileName = "";
        try {
            if (file != null) {
                fileName = System.currentTimeMillis() + file.getOriginalFilename();
                String upload_file_dir=uploadPathImg;
                String destFileName =  uploadPathImg +fileName;
                File upload_file_dir_file = new File(upload_file_dir);
                if (!upload_file_dir_file.exists())
                {
                    upload_file_dir_file.mkdirs();
                }
                File targetFile = new File(upload_file_dir_file, fileName);
                file.transferTo(targetFile);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return virtualImgUrl+fileName;
    }
}

 以下便是运行结果:

参考链接:springboot 上传图片到服务器,并把图片路径存入数据库,让前端访问图片_爱笑的女孩运气不会太差的博客-CSDN博客_springboot上传图片到服务器 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值