SpringBoot+wangEditor實現圖片上傳到本地返回url回顯

HTML頁面:

<div id="editor">
//此處創建富文本區域
</div>

<script>
    $(function () {
        var E = window.wangEditor
        var editor = new E('#editor')
        // 隱藏“網絡圖片”tab
        editor.customConfig.showLinkImg = false
        // 關閉粘貼內容中的樣式
        editor.customConfig.pasteFilterStyle = false
        // 忽略粘貼內容中的圖片
        editor.customConfig.pasteIgnoreImg = false
        // 將圖片大小限制爲 3M
        editor.customConfig.uploadImgMaxSize = 3 * 1024 * 1024
        // 限制一次最多上傳 1 張圖片
        editor.customConfig.uploadImgMaxLength = 1
        editor.customConfig.uploadImgServer = '/upload'
        editor.customConfig.uploadFileName = 'myFileName'
     /*   editor.customConfig.uploadImgHeaders = {
            'Accept': 'text/x-json'
        }*/
        editor.customConfig.uploadImgHooks = {
            customInsert: function (insertImg, result, editor) {
                var url =result.data;//獲取後臺返回的url
                insertImg(url);
            }
        };
        editor.create();
        $('#editor').attr('style','height:auto;');
    })
</script>

後端代碼:

創建一個配置類:MyWebMvcConfigurerAdapter

內容如下:

 

@Configuration
public class MyWebMvcConfigurerAdapter extends WebMvcConfigurerAdapter {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry){
        //指向外部目錄
        registry.addResourceHandler("param1").addResourceLocations("param2");
        super.addResourceHandlers(registry);
    }
}
注:param1是指定的要上傳的文件夾位置(去掉盤符,在最後添加“/**” 例如:“imgUploads/**”)param2是指定的文件夾位置(帶盤符,在前面要加上“file” 例如:“file:D:/imgUploads/”)

controller層:

@RequestMapping("/upload")
@ResponseBody
public Map<String, String> upload(@RequestParam(value="myFileName") MultipartFile file, HttpServletRequest request) {
        String separator = System.getProperty("file.separator");
          separator=separator.replaceAll("\\\\","/");
        String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() +           request.getContextPath()+ separator; //獲取項目路徑+端口號 比如:http://localhost:8080/
        
    try {
        String filePath="";
        //獲取源文件
        filePath="D:/imgUploads/" ;//存儲地址,此處也可以在application.yml中配置對象用@Value("${*.**}")註解注入內容
        String filename = file.getOriginalFilename();//獲取圖片名
        String[] names=filename.split("\\.");//獲取後綴格式
        String uploadFileName=UUID.randomUUID().toString()+"."+names[names.length-1];//生成新圖片
        File targetFile = new File (filePath,uploadFileName);//目標文件
        if (!targetFile.getParentFile().exists()){
            targetFile.getParentFile().mkdirs();
        }
        //傳圖片一步到位
        file.transferTo(targetFile);
          Map<String, String> map = new HashMap<String, String>();
        map.put("data",basePath+"imgUploads/"+uploadFileName);//這裏應該是項目路徑,返回前臺url
        return map;
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return  null;
    }
}

 

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