SpringBoot實現圖片上傳demo&Nginx進行代理顯示

公司項目需要一個圖片上傳的功能,就圖片能上傳到服務器(公司用的windows服務器),然後nginx能進行代理訪問到就行了,先簡單介紹一下nginx,然後再來實現功能。

一、nginx簡介

Nginx (engine x) 是一個高性能的HTTP和反向代理web服務器,特點是佔有內存少,併發能力強,事實上nginx的併發能力在同類型的網頁服務器中表現較好。
Nginx專門爲性能優化而開發,性能是其最重要的考量,實際上非常注重效率,能經起高負載的考驗,有報告表明能支持高達50000個併發連接數。

二、反向代理

1.正向代理
在客戶端(瀏覽器)配置代理服務器,通過代理服務器進行互聯網訪問。
2.反向代理
我們只需要將請求發送到反向代理服務器,由反向代理服務器去選擇目標服務器獲取數據後,再返回給客戶端,此時反向代理服務器和目標服務器對外就是一個服務器,暴露的是代理服務器地址,隱藏了真實服務器IP地址。

三、負載均衡

增加服務器的數量,然後將請求分發到各個服務器上,將原先請求集中到單個服務器上的情況改爲分發到多個服務器上,將負載分發到不同的服務器,也就是我們所說的負載均衡。

四、動靜分離

爲了加快網站的解析速度,可以把動態頁面和靜態頁面由不同的服務器來解析,加快解析速度。減低原來單個服務器的壓力。

五、nginx常用命令

1.使用nginx操作命令前提條件:必須進行nginx的目錄

2.查看nginx的版本號
nginx -v

3.啓動nginx
nginx

4.關閉nginx
nginx -s stop

5.重新加載nginx
nginx -s reload

六、nginx的配置文件(nginx.conf)

nginx配置文件有三部分組成
1.全局塊
從配置文件開始到events塊之間的內容,主要會設置一些影響nginx服務器整體運行的配置指令。
比如:worker_processes 1; worker_processes值越大,可以支持的併發處理量也越多。

2.events塊

events塊涉及的指令主要影響nginx服務器與用戶的網絡連接。
比如:worker_connection 1024; 支持的最大連接數。

3.http塊
nginx服務器配置中最頻繁的部分,http塊也可以包括http全局塊、server塊。

七、nginx配置圖片的訪問路徑

圖片文件上傳至服務器D:/images中,然後通過IP地址/upload/加圖片名稱進行訪問。

#user  nobody;
worker_processes  1;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       mime.types;
    default_type  application/octet-stream;

    #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
    #                  '$status $body_bytes_sent "$http_referer" '
    #                  '"$http_user_agent" "$http_x_forwarded_for"';

    #access_log  logs/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;

    server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        #訪問路徑拼接 upload 訪問本地絕對路徑下的某圖片 
        location /upload/ {
        alias D:/images/;
        autoindex on;
        }

        location / {
            root   html;
            index  index.html index.htm;
        }

        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
        #    proxy_pass   http://127.0.0.1;
        #}

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #location ~ \.php$ {
        #    root           html;
        #    fastcgi_pass   127.0.0.1:9000;
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        #    include        fastcgi_params;
        #}

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #    deny  all;
        #}
    }


    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}


    # HTTPS server
    #
    #server {
    #    listen       443 ssl;
    #    server_name  localhost;

    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.key;

    #    ssl_session_cache    shared:SSL:1m;
    #    ssl_session_timeout  5m;

    #    ssl_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers  on;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}

}

配置好nginx.conf記得重啓一下服務器。效果如圖:

八、java後臺代碼

/**
 * 文件上傳
 */
@RestController
public class FileController {

    @PostMapping(value = "/fileUpload")
    public String fileUpload(@RequestParam(value = "file") MultipartFile file) {
        if (file.isEmpty()) {
            System.out.println("請選擇圖片");
        }
        String fileName = file.getOriginalFilename();  // 文件名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));  // 後綴名
        String filePath = "D:/images/"; // 上傳後的路徑
        fileName = UUID.randomUUID() + suffixName; // 新文件名
        File dest = new File(filePath + fileName);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //返回圖片名稱
        return fileName;
    }
}

這裏將圖片上傳至D:/images文件夾中,因爲前面配置了nginx的緣故,我這裏是在本地測試的,直接使用localhost/upload/+返回的圖片名稱就可以訪問到了。

如果想要通過項目的地址外加端口號進行訪問的話,可以配置一個資源映射路徑。

/**
 * 資源映射路徑
 */
@Configuration
public class MyWebMvcConfig implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/upload/**").addResourceLocations("file:D:/images/");
    }
}

like this!

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章