SpringBoot 上傳圖片及搭建圖片服務器

咱們平時在上傳圖片、文件的時候都會用到form表單進行上傳,可是上傳以後會跳轉頁面。這裏我用第二種方式上傳:採用Ajax 異步請求的方式。html

一、後端接口設計前端

 

/**
 * 上傳文件
 * @param file
 * @return  * @throws Exception
 */
@RequestMapping(value = "/upload",method = RequestMethod.POST)
public CommonResult upload(CommonResult commonResult,
                           @RequestParam(value = "file",required = false) MultipartFile file) throws Exception {

    String fileName = "";
    if (!file.isEmpty()) {
        BufferedOutputStream out = null;
        File fileSourcePath = new File(PATH);
        if (!fileSourcePath.exists()) {
            fileSourcePath.mkdirs();
        }
        fileName = file.getOriginalFilename();
        LOGGER.info("上傳的文件名爲:" + fileName);
        out = new BufferedOutputStream(
                new FileOutputStream(new File(fileSourcePath, fileName)));
        out.write(file.getBytes());
        out.flush();
        System.out.println(fileName.toString());
    }
    commonResult.setCodeAndMessage(ApiStatusCode.SUCCESS,"");
    commonResult.setData(fileName);
    return commonResult;

}

 

其中commonResult是本身定義的統一返回結果的封裝。ajax

二、前端設計json

 

<form id = "upload" method="POST"  enctype="multipart/form-data">
    <input type="file" name="file"  id = "pic"/>
    <input type="button" value="提交" id = "upload_button" />
</form>

給這個button添加點擊事件:後端

 

/**
 * 上傳封面,上傳成功後將圖片的URl填入
 *
 */
$("#upload_button").click(function () {
    var formData = new FormData($("#upload")[0]);
    api.uploadFile(formData).then(function (res) {
        if (res.code == 200) {
            var imageName = res.data;
    //        var imageUrl  = HOST_IMAGES + imageName;
            // 給封面 賦值
     //       $("#txt_images").val(imageUrl);
        }
    })
});

 

Ajax 異步請求發送api

 

/**
 * 上傳文件
 * @returns {*}
 */
uploadFile : function (formData) {
    var url = HOST_INFOGRAPHIC + "upload";
    return $.ajax({
        url : url,
        type: 'post',
        data : formData,
        //dataType:'jsonp'
        processData:false,
        contentType:false
    })
}

以上就是前端和後端主要的代碼設計了。圖片已經被上傳到指定的服務器的路徑上面。本例中我經過Nginx服務器本身搭建一個圖片服務器,這樣就能夠經過http請求也能訪問到上傳上去的圖片了,這裏就不說Nignx服務器的搭建了,能夠參考個人這篇博客:http://blog.csdn.net/wusd1256/article/details/77772675服務器

這裏我主要說下搭建圖片服務Nginx的配置。
    server {
        listen       80;
        server_name  dev.test.com;app

        location / {
        
            root   D:/idea-workspase/Journal/app;
            index  index.html;
        }異步

        location /w-api {
            proxy_pass http://127.0.0.1:8088;
        }
        
        location  /images/ {
            root     D:/idea-workspase/infographic_cms; 
            autoindex on;
        }ide

    
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

    }

這裏我主要說下搭建圖片服務Nginx的配置。

訪問這個連接 http://dev.test.com/images/111.png  就能夠訪問到上傳的圖片111.png了。

相關文章
相關標籤/搜索