java Web項目上傳圖片儲存到項目下

 @RequestMapping(value = "/mi/upload", method = RequestMethod.POST)
    @ResponseBody
    public MyResponse upload(HttpServletRequest request, @RequestParam("file") MultipartFile file) {
        long size = file.getSize();
        if(size>1024*1024*2){
            throw new MyException("圖片大小不能超過2M");
        }
        String classpath = this.getClass().getResource("/").getPath().replaceFirst("/", "");
        //String webappRoot = classpath.replaceAll("WEB-INF/classes/", "");
        //可以自定義路徑
        File dir = new File(classpath+"/images");
        if(!dir.isDirectory()){
            dir.mkdirs();
        }
        String accessUrl =  "/images/"+System.currentTimeMillis()+file.getName()+".jpg";
        try {
            File file1 = new File(classpath+accessUrl);
            file.transferTo(file1);
        } catch (IOException e) {
            e.printStackTrace();
            throw new MyException("上傳失敗");
        }
  }

2.讀取本地文件內容

//        String filepath = "E:/upload/test.txt";//E盤下的文件夾的目錄
//        File targetFile = new File(filepath);//File類型可以是文件也可以是文件夾
//
//        // File targetFile = new File(path);
//        if (!targetFile.exists()) {
//            targetFile.mkdirs();
//        }
//        //保存到本地的文件
//        // File saveFile = new File(path + fileName);
//        FileInputStream fileInput = null;
//        String rs = "";
//        try {
//            // 通過File對象構建一個流對象
//            fileInput = new FileInputStream(targetFile);
//            // 讀取數據,並將讀取的數據存儲在數組中
//            byte[] data = new byte[(int) targetFile.length()];
//            // 讀取流中的第一個字節數據
//            int n = fileInput.read();
//            // 讀取的遊標位置
//            int i = 0;
//            // 判斷是否讀到最後一個字符
//            while (n != -1) {
//                data[i] = (byte) n;
//                i++;
//                n = fileInput.read();
//            }
//            rs = new String(data, "GBK");
//            System.out.println(rs);
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        try {
//            file.transferTo(targetFile);
//            return new MyResponse(rs);
//        } catch (Exception e) {
//            e.printStackTrace();
//            return new MyResponse(ResponseCode.OPERATE_FAIL, e.getMessage());
//        }

 

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