天天看點

MultipartFile上傳檔案

MultipartFile上傳檔案

/**
     * 添加最新版本
     *
     * @param appVersion
     * @param appInfoId
     * @param model
     * @return
     */
    @RequestMapping("/addAppVersion")
    public String addAppVersion(@RequestParam(value = "apkFile", required = false) MultipartFile file, AppVersion appVersion, int appInfoId, Model model, HttpSession session, HttpServletRequest request) {
        String PicPath = null;
        File targetFile = null;
        String fileName = null;
        //判斷檔案是否為空
        if (!file.isEmpty()) {
            String path = session.getServletContext().getRealPath(request.getContextPath() + "/static/" + "uploadfiles");//檔案夾在項目中的位址
            String originalFilename = file.getOriginalFilename();//原檔案名
            String suffix = FilenameUtils.getExtension(originalFilename);//擷取原檔案字尾
            int fileSize = 512000000;
            if (file.getSize() > fileSize) {
                model.addAttribute("errorMessage", "上傳檔案大小不得超過500MB");
                return "redirect:/appInfo/toAddAppVersion";
            }//上傳檔案格式正确
            else if (suffix.equalsIgnoreCase("apk")) {
                Random random = new Random();
                fileName = "com." + System.currentTimeMillis() + random.nextInt(1000000) + "APP.apk";
                targetFile = new File(path, fileName);
                if (!targetFile.exists()) targetFile.mkdirs();
                //儲存
                try {
                    file.transferTo(targetFile);
                } catch (IOException e) {
                    model.addAttribute("errorMessage", "上傳檔案失敗!");
                    e.printStackTrace();
                    return "redirect:/appInfo/toAddAppVersion";
                }
                PicPath = path + "/" + fileName;
            } else {
                model.addAttribute("errorMessage", "上傳檔案格式不正确!");
                return "redirect:/appInfo/toAddAppVersion";
            }

        }
        DevUser devUser = (DevUser) session.getAttribute(Constants.DEV_SESSION);
        appVersion.setCreatedBy(devUser.getId());
        Date date = new Date();
        appVersion.setCreationDate(date);
        if (fileName != null) {
            appVersion.setDownloadLink(request.getContextPath() + "/static/" + "uploadfiles/" + fileName);
            appVersion.setApkLocPath(PicPath);
            appVersion.setApkFileName(fileName);
        }
        //添加appVersion
        int i = appVersionService.AddAppVersion(appVersion);
        if (i < 1) {
            model.addAttribute("message", "添加版本失敗!");
            return "redirect:/appInfo/toAddAppVersion";
        }
        //把添加後的版本id放入appInfo中
        int id = appVersion.getId();
        AppInfo appInfo = appInfoService.selectAppInfoById(appInfoId);
        appInfo.setVersionId(id);
        return "forward:/appInfo/appList";
    }