1. 程式人生 > >Spring boot 上傳圖片

Spring boot 上傳圖片

@ResponseBody
    @RequestMapping(path = "/save_photo", method={RequestMethod.POST})
    public void addDish(@RequestParam("photos") MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws Exception
    {
        String path = null;// 檔案路徑
        String json = "";
        if (file!=null) {// 判斷上傳的檔案是否為空

            String type = null;// 檔案型別
            String fileName = file.getOriginalFilename();// 檔案原名稱
            System.out.println("上傳的檔案原名稱:"+fileName);
            // 判斷檔案型別
            type = fileName.indexOf(".")!=-1?fileName.substring(fileName.lastIndexOf(".")+1, fileName.length()):null;
            if (type!=null) {// 判斷檔案型別是否為空
                if ("GIF".equals(type.toUpperCase())||"PNG".equals(type.toUpperCase())||"JPG".equals(type.toUpperCase())) {
                    // 專案在容器中實際釋出執行的根路徑
                    String realPath = request.getSession().getServletContext().getRealPath("/");
                    // 自定義的檔名稱
                    String trueFileName = String.valueOf(System.currentTimeMillis()) + "." + type;
                    // 設定存放圖片檔案的路徑
                    path = realPath+/*System.getProperty("file.separator")+*/trueFileName;
                    System.out.println("存放圖片檔案的路徑:"+path);
                    // 轉存檔案到指定的路徑
                    file.transferTo(new File(path));
                    System.out.println("檔案成功上傳到指定目錄下");                  
                    }
                    json = "{\"res\":1}";
                }else {
                    System.out.println("不是我們想要的檔案型別,請按要求重新上傳");
                    //return null;
                    json = "{\"res\":0}";
                }
            }else {
                System.out.println("檔案型別為空");
                //return null;
                json = "{\"res\":0}";
            }
        }else {
            System.out.println("沒有找到相對應的檔案");
            json = "{\"res\":0}";
            //return null;
        }
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().print(json);
    }

首先注意的是引數要加

@RequestParam("photos") MultipartFile file

你的html可能就類似這樣的

<form action="/save_photo" enctype="multipart/form-data" method="post">
<input type="file" name="photos" /> <br> 
<input type="submit" value="上傳" /> 
</form>