1. 程式人生 > >java檔案上傳

java檔案上傳

檔案上傳有很多種格式

第一種:Base64: 筆記直接上程式碼:

	  @PostMapping("/fileUploading")
    public AjaxResult uploadIng(@RequestParam(required = false, value = "fileStr") String fileStr, HttpServletRequest request)  {

        Base64DecodedMultipartFile base64DecodedMultipartFile = null;
        if (null != fileStr && !fileStr.isEmpty()) {
            base64DecodedMultipartFile = (Base64DecodedMultipartFile) Base64StrToImage.base64MutipartFile(fileStr);
            List<String> stringList = null;
            if (null != base64DecodedMultipartFile && !base64DecodedMultipartFile.equals("")) {
                FileUploading fileUploading = new FileUploading();
                try {
                    stringList = fileUploading.phtoUpload(base64DecodedMultipartFile, request);
                } catch (IOException e) {
                    e.printStackTrace();
                    return AjaxResult.error("資訊異常"+e, 1);
                }
            }
            return AjaxResult.successState("上傳成功", 0, stringList);
        } else {
            return AjaxResult.error("資訊異常", 1);
        }
    }
public List<String> phtoUpload(Base64DecodedMultipartFile base64DecodedMultipartFile, HttpServletRequest request)throws IllegalStateException, IOException {
        List<String> list = new ArrayList<>();
        if (base64DecodedMultipartFile != null && !base64DecodedMultipartFile.isEmpty()) {
                list = saveFileBase64(base64DecodedMultipartFile, list, request);

        } else {
            System.out.println("未找到相對應的圖片");
            return null;
        }
        return list;
    }
private List<String> saveFileBase64(Base64DecodedMultipartFile file, List<String> list, HttpServletRequest request)throws IllegalStateException, IOException  {

        if (file != null) {// 判斷上傳的檔案是否為空
            String path = null;// 檔案路徑
            String type = null;// 檔案型別
            String url = "";
            String fileName = file.getOriginalFilename();// 檔案原名稱
            System.out.println("上傳的檔案原名稱:" + fileName);
            // 判斷檔案型別
            type = fileName.indexOf(".") != -1 ? fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()) : null;
            if (type != null) {// 判斷檔案型別是否為空
                if ("JPEG".equals(type.toUpperCase()) || "GIF".equals(type.toUpperCase()) || "PNG".equals(type.toUpperCase()) || "JPG".equals(type.toUpperCase())) {
                    String returnUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath()+"/upload";//儲存路徑
                    // 專案在容器中實際釋出執行的根路徑
                    String realPath = request.getSession().getServletContext()
                            .getRealPath("/upload/");
                    // 自定義的檔名稱
                    String trueFileName = new Date().getTime()+"_"+file.getOriginalFilename();
                    // 設定存放圖片檔案的路徑
                    path = realPath + trueFileName;
                    System.out.println("存放圖片檔案的路徑:" + path);
                    File saveDir = new File(path);
                    if (!saveDir.getParentFile().exists())
                        saveDir.getParentFile().mkdirs();
                    // 轉存檔案到指定的路徑
                    file.transferTo(saveDir);
                    url = returnUrl +"/"+trueFileName;
                    list.add(url);
                    System.out.println("檔案成功上傳到指定目錄下");
                } else {
                    System.out.println("不是我們想要的檔案型別,請按要求重新上傳");
                    return null;
                }
            } else {
                System.out.println("檔案型別為空");
                return null;
            }
        } else {
            System.out.println("沒有找到相對應的檔案");
            return null;
        }
        return list;
    }

第二種使用 MultipartFile:

 @PostMapping(value = "/photoUpload")
    public FileDataResult<Object> photoUpload(MultipartFile file, HttpServletRequest request, HttpServletResponse response, HttpSession session) throws IllegalStateException, IOException {
        FileDataResult<Object> resultData = new FileDataResult<>();
        if (file != null) {// 判斷上傳的檔案是否為空
            String path = null;// 檔案路徑
            String type = null;// 檔案型別
            String url = "";
            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())|| "JPEG".equals(type.toUpperCase())|| "MP4".equals(type.toUpperCase())|| "3GP".equals(type.toUpperCase()) ) {
                    String returnUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath()+"/upload";//儲存路徑
                    // 專案在容器中實際釋出執行的根路徑
                    String realPath = request.getSession().getServletContext()
                            .getRealPath("/upload/");
                    // 自定義的檔名稱
                    String trueFileName = new Date().getTime()+"_"+file.getOriginalFilename();
                    // 設定存放圖片檔案的路徑
                    path = realPath + trueFileName;
                    System.out.println("存放圖片檔案的路徑:" + path);
                    File saveDir = new File(path);
                    if (!saveDir.getParentFile().exists())
                        saveDir.getParentFile().mkdirs();
                    // 轉存檔案到指定的路徑
                    file.transferTo(saveDir);
                    url = returnUrl +"/"+trueFileName;
                    resultData.setData(url);
                    System.out.println("檔案成功上傳到指定目錄下");
                } else {
                    System.out.println("不是我們想要的檔案型別,請按要求重新上傳");
                    return null;
                }
            } else {
                System.out.println("檔案型別為空");
                return null;
            }
        } else {
            System.out.println("沒有找到相對應的檔案");
            return null;
        }
        return resultData;
    }

第三種 HttpServletRequest:

 @RequestMapping("/testfile")
    @SuppressWarnings({"unchecked","rawtypes"})
    public  FileDataResult<Object> testFile( HttpServletRequest request,HttpServletResponse resp,HttpSession session) throws IOException {//value的名字一定要叫upfile,這是ueditor寫好的引數名稱
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        // 獲得上傳的檔案(根據前臺的name名稱得到上傳的檔案)
        MultiValueMap<String, MultipartFile> multiValueMap = multipartRequest.getMultiFileMap();
        List<MultipartFile> upfile = multiValueMap.get("file");
        FileDataResult<Object> fileUploading= null;
        if(!upfile.isEmpty()){
            for (MultipartFile file : upfile) {
                fileUploading= new FileUploadingController().photoUpload(file,request,resp,session);
            }
        }
        return fileUploading;
    }

第三種就是通過request種獲取file ,然後可以通過第二種方式將file 上傳上去;

在這裡插入圖片描述