欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

springboot項(xiàng)目訪問圖片的3種實(shí)現(xiàn)方法(親測(cè)可用)

 更新時(shí)間:2023年09月27日 14:50:39   作者:java程序員CC  
本文主要介紹了springboot項(xiàng)目訪問圖片的3種實(shí)現(xiàn)方法,通過springboot項(xiàng)目訪問除項(xiàng)目根目錄之外的其它目錄的圖片,具有一定的參考價(jià)值,感興趣的可以了解一下

前言

主要介紹通過springboot項(xiàng)目訪問除項(xiàng)目根目錄之外的其它目錄的圖片。

一、配置類實(shí)現(xiàn)WebMvcConfigurer

WebMvcConfigurer是spring內(nèi)部提供的一種配置接口,代替了傳統(tǒng)的xml配置文件形式,

二、使用步驟

1.編寫配置類

代碼如下(示例):

@Configuration
public class ResourcesConfig implements WebMvcConfigurer
{
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry)
    {
        /** 通過url訪問項(xiàng)目外的目錄圖片*/
        registry.addResourceHandler("/cert/**").addResourceLocations("file:/D:/Download/img/");
    }
}

代碼截屏

2.讀入數(shù)據(jù)

代碼片段: 

<img src="/cert/4.jpg" style="width: 1in; height: 1in;">
<img src="/cert/1.jpg"  style="width: 1in; height: 1in;">

截屏

因?yàn)閐emo是在若依框架的基礎(chǔ)上實(shí)現(xiàn)的所以自定義函數(shù)就沒有貼上來,因?yàn)槊總€(gè)人的需求不一樣,此處主要是實(shí)現(xiàn)通過方法實(shí)現(xiàn)對(duì)項(xiàng)目根路徑之外的圖片訪問,效果是都能實(shí)現(xiàn)的

到這里想必 大家已經(jīng)知道了,就是通過配置使自定義的“cert/**”代替了指定的盤符路徑。進(jìn)階思考一下,我們的想通過動(dòng)態(tài)數(shù)據(jù)訪問動(dòng)態(tài)圖片(用戶頭像,每個(gè)用戶都有自己獨(dú)一無二的圖片),那么我們只需要將圖片路徑存儲(chǔ)在數(shù)據(jù)庫中即可,通過id或其它字段將用戶頭像的存儲(chǔ)路徑與用戶進(jìn)行綁定,不需要存儲(chǔ)圖片文件本身。

數(shù)據(jù)庫存儲(chǔ)的數(shù)據(jù)(ps:不推薦這樣存儲(chǔ)叫什么1,2,3之類的名稱,我這里是為了快速達(dá)到目的,因?yàn)樯婕暗缴蟼魑募?。?yīng)該在那里的圖片名稱應(yīng)該是日期+UUID隨機(jī)數(shù)組成,后面也會(huì)更新)

代碼片段:

<img src="/cert/' + 后端傳過來遍歷的數(shù)據(jù)集.圖片路徑對(duì)應(yīng)的實(shí)體屬性 + '" style="width: 1in; height: 1in;">
<img src="/cert/' + row.certAddress2 + '" style="width: 1in; height: 1in;">

 實(shí)現(xiàn)效果:

二、Nginx反向代理實(shí)現(xiàn)

2.1:安裝nginx

傻瓜式安裝,點(diǎn)擊下一步下一步,記住你的安裝目錄就行。

配置nginx配置文件,我的安裝在D盤,

 編輯nginx.conf

 找到server{那一行,箭頭1:是配置監(jiān)聽端口,我這里設(shè)置的是8090;箭頭2:是配置域名(就是類似一www.baidu.com,www.12306.com等等這就叫域名),我這里是本地ip沒法綁定域名就設(shè)置ip代替了

 !!!箭頭3這里就是最重要的一步映射文件路徑了配置的代碼我貼下面了

配置文件片段:  

        listen       8090;
        server_name  192.168.61.1;
        location / {       
            root   html;
            index  index.html index.htm;  
        }
        location /File/ {           
            root   D:\Download\img;       
            rewrite ^/File/(.*)$ /$1 break;   
        }

前端代碼:

                    {
                        field: 'certAddress1',
                        title: '證件正面',
                        formatter: function(value, row, index) {
                            return '<img src="http://192.168.61.1:8090/File/' + row.certAddress1 + '" style="width: 1in; height: 1in;">';
                        }
                    },
                    {
                        field: 'certAddress2',
                        title: '證件背面',
                        formatter: function(value, row, index) {
                            return '<img src="http://192.168.61.1:8090/File/' + row.certAddress2 + '" style="width: 1in; height: 1in;">';
                        }
                    },

實(shí)現(xiàn)效果:

說明:通過nginx反向代理的路徑不需要寫在方法一的配置類中(因?yàn)槲覀冊(cè)趎ginx的配置文件中寫好了),寫了也沒關(guān)系,這幾種方式都是互不影響的

三: 通過七牛云OSS訪問圖片

1注冊(cè)七牛云

注冊(cè)成功后點(diǎn)擊對(duì)象存儲(chǔ)

3:新建存儲(chǔ)空間。地址隨便選

4:獲取外鏈域名(注意這個(gè)域名是七牛云提供的臨時(shí)域名,有效期只有30天)。到期后就重新創(chuàng)建新的存儲(chǔ)空間,又會(huì)有新的外鏈域名。這個(gè)是免費(fèi)的就不要要求那么多了

5:點(diǎn)擊“個(gè)人中心”—>“密鑰管理”獲取你的AK,SK

到目前為止。七牛云的存儲(chǔ)服務(wù)空間就完全搭建好了。對(duì)于使用七牛云文件存儲(chǔ)器現(xiàn)在只需要用到我們上面提到的3個(gè)東西。

1:空間名稱、2:外鏈域名、3:密鑰AK、SK。

測(cè)試文件上傳,然后查看圖片

controller代碼

@RestController
public class UploadController {
    @Resource
    private IUploadOssService uploadService;
    @PostMapping("/oss/upload")
    public AjaxResult uploadImgOss(@RequestParam("file")MultipartFile file) throws InvalidExtensionException {
       return uploadService.uploadImg(file);
    }
}

service接口代碼

public interface IUploadOssService {
    AjaxResult uploadImg(MultipartFile img) throws InvalidExtensionException;
}

service實(shí)現(xiàn)類代碼

@Service
@Data
@ConfigurationProperties(prefix = "oss")
public class UploadOssServiceImpl implements IUploadOssService {
    @Override
    public AjaxResult uploadImg(MultipartFile img) throws InvalidExtensionException {
        if (!Objects.requireNonNull(img.getOriginalFilename()).isEmpty()) {
            //判斷文件類型
            //獲取原始文件名
            String originalFilename = img.getOriginalFilename();
            //對(duì)原始文件名進(jìn)行判斷
            if (!originalFilename.endsWith(".png") && !originalFilename.endsWith(".jpg")) {
                String[] allowedExtension = {".png", ".jpg"};
                throw new InvalidExtensionException(allowedExtension, lastName(originalFilename), originalFilename);
            }
            //如果判斷通過上傳文件到OSS
            String filePath = PathUtils.generateFilePath(originalFilename);
            String url = uploadOss(img, filePath);
            return AjaxResult.success(url);
        }
        return AjaxResult.error("上傳文件為空");
    }
        // 獲取文件后綴名
    private String lastName(String fileName){
            if(fileName.lastIndexOf(".")==-1){
                return "";//文件沒有后綴名的情況
            }
            //此時(shí)返回的是帶有 . 的后綴名
            return fileName.substring(fileName.lastIndexOf("."));
        }
    private String accessKey;
    private String secretKey;
    private String bucket;
    private String uploadOss(MultipartFile imgFile, String filePath){
        //構(gòu)造一個(gè)帶指定 Region 對(duì)象的配置類
        Configuration cfg = new Configuration(Region.autoRegion());
        //...其他參數(shù)參考類注釋
        UploadManager uploadManager = new UploadManager(cfg);
        //默認(rèn)不指定key的情況下,以文件內(nèi)容的hash值作為文件名
        String key = filePath;
        try {
            InputStream inputStream = imgFile.getInputStream();
            Auth auth = Auth.create(accessKey, secretKey);
            String upToken = auth.uploadToken(bucket);
            try {
                Response response = uploadManager.put(inputStream,key,upToken,null, null);
                //解析上傳成功的結(jié)果
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                System.out.println(putRet.key);
                System.out.println(putRet.hash);
                //下面這個(gè)七牛云cnd臨時(shí)域名有效期只有一個(gè)月,失效后需要去七牛云復(fù)制新生成的
                return "你的七牛云外鏈域名"+key;
            } catch (QiniuException ex) {
                Response r = ex.response;
                System.err.println(r.toString());
                try {
                    System.err.println(r.bodyString());
                } catch (QiniuException ex2) {
                    //ignore
                }
            }
        } catch (Exception ex) {
            //ignore
        }
        return "www";
    }
}

開始測(cè)試圖片上傳

測(cè)試通過,圖片上傳成功,

msg返回了一段地址。平時(shí)我們?cè)谧鰣D片上傳時(shí)。就可以調(diào)用這個(gè)接口.然后將這段數(shù)據(jù)存入數(shù)據(jù)庫。

前端圖片展示部分代碼:

 <el-table v-loading="loading" :data="movieList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="主鍵" v-if="false" align="center" prop="mId"/>
      <el-table-column label="電影名" align="center" prop="mName"/>
      <el-table-column label="封面" align="center" prop="mImg">
      <template slot-scope="scope">
        <img :src="'http://'+scope.row.mImg" alt="" :width="90" :height="120">
      </template>
      </el-table-column>
      <el-table-column label="電影欄目" align="center" prop="cId"/>
      <el-table-column label="類型" :show-overflow-tooltip="true" align="center" prop="mClass"/>
      <el-table-column label="簡介" :show-overflow-tooltip="true" align="center" prop="mInfo"/>
      <el-table-column label="時(shí)長" align="center" prop="mDuration"/>
      <el-table-column label="地區(qū)" align="center" prop="mAddr"/>
      <el-table-column label="評(píng)分" align="center" prop="mScore"/>
      <el-table-column label="上映年份" align="center" prop="mYear" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.mYear, '{y}-{m}-vvxyksv9kd') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['appmovie:movie:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['appmovie:movie:remove']"
          >刪除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

就可以直接訪問了

總結(jié)

到此這篇關(guān)于springboot項(xiàng)目訪問圖片的3種實(shí)現(xiàn)方法(親測(cè)可用)的文章就介紹到這了,更多相關(guān)springboot項(xiàng)目訪問圖片內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論