天天看点

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";
    }