springboot文件上傳: 單個文件上傳 和 多個文件上傳


單個文件上傳

 

//文件上傳統一處理
        @RequestMapping(value = "/upload",method=RequestMethod.POST)
        @ResponseBody
        public WangEditor uploadFile(
                @RequestParam("myFile") MultipartFile multipartFile,
                HttpServletRequest request) {
     
            try {
                /*// 獲取項目路徑
                String realPath = request.getSession().getServletContext()
                        .getRealPath("");
                InputStream inputStream = multipartFile.getInputStream();
                String contextPath = request.getContextPath();
                // 服務器根目錄的路徑
                String path = realPath.replace(contextPath.substring(1), "");
                // 根目錄下新建文件夾upload,存放上傳圖片
                String uploadPath = path + "uploaded/";*/
                // 獲取文件名稱
                
                InputStream inputStream = multipartFile.getInputStream();
                String originalFilename = multipartFile.getOriginalFilename();
                String extSign = originalFilename.substring(originalFilename.lastIndexOf("."));
                String newFilename = UUID.randomUUID().toString() + extSign;
                
                // 將文件上傳的服務器根目錄下的upload文件夾
                String destFileName = request.getServletContext().getRealPath("") + "uploaded" + File.separator + newFilename;
                File file = new File(destFileName);
                FileUtils.copyInputStreamToFile(inputStream, file);
                // 返回圖片訪問路徑
                String url = request.getScheme() + "://" + request.getServerName()
                        + ":" + request.getServerPort() + request.getContextPath() +"/uploaded/" + newFilename;
                
                String [] str = {url};
                WangEditor we = new WangEditor(str);
                return we;
            } catch (IOException e) {
                //log.error("上傳文件失敗", e);
            }
            return null;
     
        }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM