SpringBoot利用Nginx作為檔案伺服器實現檔案上傳和訪問

未來阿里P9發表於2020-10-12

本來使用springboot做的檔案上傳本地測試沒問題,但是後端部署到公司的伺服器以後,前後端聯調就會上傳檔案後,根據返回路徑訪問不到圖片(linux並不會讓你直接根據域名/路徑/檔名 的方式獲取資源)。解決辦法:使用nginx反向代理。

1.提前在伺服器的nginx配置


    server {
        listen       80;
        server_name  域名;

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

		#以下為我新增的配置
        location ~ .(jpg|png|jpeg|gif|bmp)$ {   #可識別的檔案字尾
            root /usr/local/webserver/nginx/image/;     #圖片的對映路徑
            autoindex on;       #開啟自動索引
           # expires 1h;         #過期時間
        }
        #至此結束

    }

簡單的說就是nginx監聽了80埠,只要是.(jpg|png|jpeg|gif|bmp)結尾的url都會去/usr/local/webserver/nginx/image/下面找對應的檔案。

2.專案配置檔案

#檔案上傳配置
spring.servlet.multipart.enabled=true
#單個檔案最大大小
spring.servlet.multipart.max-file-size=30MB
#一次請求檔案最大大小
spring.servlet.multipart.max-request-size=100MB
#檔案儲存路徑
#linux下檔案的上傳路徑
file.upload.path=/usr/local/webserver/nginx/image/
#檔案訪問路徑
file.coming.path=http://ip:nginx監聽的埠/

3.後端檔案上傳介面

import cn.anson.AdminAnsonApplication;
import cn.anson.model.Result;
import cn.anson.model.ResultCodeEnum;
import cn.anson.model.vo.UploadVO;
import cn.anson.utils.MyException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * @author yhd
 * @createtime 2020/10/11 16:40
 */
@CrossOrigin
@Slf4j
@RestController
@RequestMapping("/api/img")
public class ImgUpLoadController {

    @Value("${file.upload.path}")
    private String fileSavePath;

    @Value("${file.coming.path}")
    private String fileComingPath;

    @PostMapping("upload")
    public Result<UploadVO> updloadImg(MultipartFile upload,HttpServletRequest request){
        try {

            //獲取檔案上傳路徑
            String path = fileSavePath;
            log.info("檔案上傳路徑為:"+path);
            File file = new File(path);
            //判斷不存在該目錄就建立
            if (!file.exists()){
                file.mkdirs();
            }
            //獲取檔名
            String filename = upload.getOriginalFilename();
            log.info(filename);
            //起別名
            String s = UUID.randomUUID().toString().replace("-", "").toUpperCase();
            filename=s+filename;
            //開始上傳
            upload.transferTo(new File(file,filename));

            UploadVO uploadVO = new UploadVO();
            uploadVO.setFileName(fileComingPath+filename);
            log.info("最終檔案的訪問路徑:"+uploadVO.getFileName());
            return Result.ok(uploadVO);
        } catch (IOException e) {
            log.error("圖片上傳失敗"+upload.getOriginalFilename());
            throw new MyException(ResultCodeEnum.SERVICE_ERROR);
        }
    }
}

4.使用postMan測試

{
    "code": 200,
    "message": "成功",
    "data": {
        "fileName": "http://ip:nginx監聽的埠/57A05F7EC8524363962403F1C539FD2Atimg.jpg"
    },
    "ok": true
}

點選訪問這個路徑
在這裡插入圖片描述
成功訪問到。

補充:pom.xml

        <!-- Apache工具元件 -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.8.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-io</artifactId>
            <version>1.3.2</version>
        </dependency>
        <dependency>
            <groupId>commons-net</groupId>
            <artifactId>commons-net</artifactId>
            <version>3.6</version>
        </dependency>
        <!-- 檔案上傳元件 -->
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.3</version>
        </dependency>
        <dependency>
            <groupId>com.jcraft</groupId>
            <artifactId>jsch</artifactId>
            <version>0.1.54</version>
        </dependency>
        <dependency>
            <groupId>joda-time</groupId>
            <artifactId>joda-time</artifactId>
            <version>2.10.3</version>
        </dependency>

相關文章