Java Code Examples for org.springframework.web.multipart.MultipartFile#isEmpty()

The following examples show how to use org.springframework.web.multipart.MultipartFile#isEmpty() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: UserResource.java    From albedo with GNU Lesser General Public License v3.0 6 votes vote down vote up
@PostMapping(value = "/upload")
@PreAuthorize("@pms.hasPermission('sys_user_upload')")
@Log(value = "用户管理导入")
public ResponseEntity uploadData(@RequestParam("uploadFile") MultipartFile dataFile, HttpServletResponse response) throws Exception {
	if (dataFile.isEmpty()) {
		return ResponseEntityBuilder.buildFail("上传文件为空");
	}
	ExcelUtil<UserExcelVo> util = new ExcelUtil(UserExcelVo.class);
	List<UserExcelVo> dataList = util.importExcel(dataFile.getInputStream());
	for (UserExcelVo userExcelVo : dataList) {
		if (userExcelVo.getPhone().length() != 11) {
			BigDecimal bd = new BigDecimal(userExcelVo.getPhone());
			userExcelVo.setPhone(bd.toPlainString());
		}
		userService.save(userExcelVo);
	}
	return ResponseEntityBuilder.buildOk("操作成功");

}
 
Example 2
Source File: AttachmentController.java    From spring-microservice-exam with MIT License 6 votes vote down vote up
/**
 * 上传文件
 *
 * @param file       file
 * @param attachment attachment
 * @author tangyi
 * @date 2018/10/30 21:54
 */
@PostMapping("upload")
@ApiOperation(value = "上传文件", notes = "上传文件")
@ApiImplicitParams({
        @ApiImplicitParam(name = "busiType", value = "业务分类", dataType = "String"),
        @ApiImplicitParam(name = "busiId", value = "业务Id", dataType = "String"),
        @ApiImplicitParam(name = "busiModule", value = "业务模块", dataType = "String"),
})
@Log("上传文件")
public ResponseBean<Attachment> upload(@ApiParam(value = "要上传的文件", required = true) @RequestParam("file") MultipartFile file,
                                       Attachment attachment) {
    if (!file.isEmpty()) {
        try {
            attachment.setCommonValue(SysUtil.getUser(), SysUtil.getSysCode(), SysUtil.getTenantCode());
            attachment.setAttachType(FileUtil.getFileNameEx(file.getOriginalFilename()));
            attachment.setAttachSize(String.valueOf(file.getSize()));
            attachment.setAttachName(file.getOriginalFilename());
            attachment.setBusiId(attachment.getId().toString());
            attachment = UploadInvoker.getInstance().upload(attachment, file.getBytes());
        } catch (Exception e) {
            log.error("upload attachment error: {}", e.getMessage(), e);
        }
    }
    return new ResponseBean<>(attachment);
}
 
Example 3
Source File: FileManagerServiceImpl.java    From efo with MIT License 6 votes vote down vote up
@Override
public JSONObject upload(String destination, MultipartFile... files) {
    System.out.println(files.length);
    if (Checker.isNotEmpty(files)) {
        if (Checker.isWindows() && destination.length() < ValueConsts.TWO_INT) {
            destination = "C:";
        }
        for (MultipartFile file : files) {
            if (Checker.isNotNull(file) && !file.isEmpty()) {
                try {
                    file.transferTo(new File(destination + File.separator + file.getOriginalFilename()));
                } catch (IOException e) {
                    logger.error(e.getMessage());
                    return getBasicResponse(ValueConsts.FALSE);
                }
            }
        }
    }
    return getBasicResponse(ValueConsts.TRUE);
}
 
Example 4
Source File: FileUtil.java    From mall with Apache License 2.0 6 votes vote down vote up
/**
 * 保存上传的文件
 *
 * @param file
 * @return 文件下载的url
 * @throws Exception
 */
public static String saveFile(MultipartFile file) throws Exception {
    if (file == null || file.isEmpty())
        return "";
    File target = new File("file");
    if (!target.isDirectory()) {
        target.mkdirs();
    }
    String originalFilename = file.getOriginalFilename();
    MessageDigest md = MessageDigest.getInstance("MD5");
    md.update(file.getBytes());
    String fileName = (Helper.bytesToHex(md.digest(),0,md.digest().length-1)) + "." + getPostfix(originalFilename);
    File file1 = new File(target.getPath() + "/" + fileName);
    Files.write(Paths.get(file1.toURI()), file.getBytes(), StandardOpenOption.CREATE_NEW);
    return "/mall/admin/product/img/" + fileName;
}
 
Example 5
Source File: AttachmentRestSupportImpl.java    From spring-backend-boilerplate with Apache License 2.0 6 votes vote down vote up
@Override
public FileObject uploadAvatar(UploadFileRequest uploadFileRequest,
							   HttpServletRequest request,
							   HttpServletResponse response) throws IOException {
	validate(uploadFileRequest);

	MultipartFile multipartFile = HttpMultipartUtils.resolveMultipartFile(request);
	if (multipartFile == null || multipartFile.isEmpty()) {
		throw new FileStorageException("The multipart of http request is required.");
	}

	FileStorageRequest fileStorageRequest = buildFileStorageRequest(multipartFile, uploadFileRequest);

	File tempFile = new File(FileUtils.getTempDirectory(), UUID.randomUUID() + ".tmp");
	multipartFile.transferTo(tempFile);
	File resizedTempFile = new File(FileUtils.getTempDirectory(), UUID.randomUUID() + ".tmp");

	ImageUtils.zoomBySquare(tempFile, resizedTempFile, 128, true);

	return doUpload(fileStorageRequest, resizedTempFile);
}
 
Example 6
Source File: UploadController.java    From spring-admin-vue with Apache License 2.0 6 votes vote down vote up
/**
 * 用户头像上传
 *
 * @param file
 * @return java.io.File
 * @throws IOException
 * @author Wang Chen Chen<[email protected]>
 * @date 2019/12/13 23:03
 */
@ApiOperation(value = "头像上传", notes = "普通的图片上传:200px * 200px")
@PostMapping("/avatar")
public JsonResult uploadAvatar(MultipartFile file) throws IOException {
    if (file.isEmpty() || StringUtils.isEmpty(file.getOriginalFilename())) {
        JsonResult.fail("头像不能为空");
    }
    String contentType = file.getContentType();
    if (!contentType.contains("")) {
        JsonResult.fail("头像格式不能为空");
    }
    String reg = ".+(.JPEG|.jpeg|.JPG|.jpg|.png|.PNG)$";
    Matcher matcher = Pattern.compile(reg).matcher(file.getOriginalFilename());
    // 校验 图片的后缀名 是否符合要求
    if (matcher.find()) {
        Map<String, String> map = uploadFile(file, 200, 200);
        return JsonResult.success(map);
    }
    return JsonResult.fail("头像格式不正确,只可以上传[ JPG , JPEG , PNG ]中的一种");
}
 
Example 7
Source File: CmmnDeploymentsClientResource.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
/**
 * POST /rest/admin/cmmn-deployments: upload a form deployment
 */
@PostMapping(produces = "application/json")
public JsonNode handleCmmnFileUpload(HttpServletRequest request, @RequestParam("file") MultipartFile file) {
    if (!file.isEmpty()) {
        try {
            ServerConfig serverConfig = retrieveServerConfig(EndpointType.CMMN);
            String fileName = file.getOriginalFilename();
            if (fileName != null && (fileName.endsWith(".cmmn") || fileName.endsWith(".xml"))) {

                return clientService.uploadDeployment(serverConfig, fileName, file.getInputStream());

            } else {
                LOGGER.error("Invalid cmmn deployment file name {}", fileName);
                throw new BadRequestException("Invalid file name");
            }

        } catch (IOException e) {
            LOGGER.error("Error deploying form upload", e);
            throw new InternalServerErrorException("Could not deploy file: " + e.getMessage());
        }

    } else {
        LOGGER.error("No cmmn deployment file found in request");
        throw new BadRequestException("No file found in POST body");
    }
}
 
Example 8
Source File: IndexController.java    From ssm-demo with MIT License 5 votes vote down vote up
@RequestMapping("testForm")
public String testForm(MultipartFile file, HttpServletRequest request) throws IllegalStateException, IOException{
	LOG.info("上传测试......");
	if(file.isEmpty()){
		return "ssm";
	}
	String fname = file.getOriginalFilename();
	LOG.info("文件名:"+fname);
	File localFile = new File("D:\\img", UUID.randomUUID()+fname.substring(fname.lastIndexOf(".")));
	if(!localFile.exists()){
		localFile.mkdirs();
	}
	file.transferTo(localFile);
	return "ssm.html";
}
 
Example 9
Source File: ApiCommController.java    From easyweb with Apache License 2.0 5 votes vote down vote up
/**
     * 上传资料
     *
     * @return
     */
    @PostMapping("/upload")
    public BaseResult upload(HttpServletRequest request, @RequestParam("file") MultipartFile file) {
        _log.debug("进入文件上传控制器");
        BaseResult result = new BaseResult(BaseResultCode.EXCEPTION, "上传失败!");
        if (!file.isEmpty()) {
            String fileOldName = file.getOriginalFilename();
            //获取文件后缀名
            String prefix = fileOldName.substring(fileOldName.lastIndexOf(".") + 1);
            String fileName = IdGen.uuid() + "." + prefix;
            _log.debug("文件名:"+fileName);
            try {
                _log.debug("开始上传文件");
                InputStream inputStream = file.getInputStream();
                boolean isOk = FtpUtil.uploadFile(ftpConfig.getHost(), ftpConfig.getUser(), ftpConfig.getPwd(), "upload", "/files", fileName, inputStream);
                if (isOk) {
                    result = new BaseResult(BaseResultCode.SUCCESS, "upload/files/" + fileName);
                }
//                FileUtil.uploadFile(file.getBytes(), filePath, fileName);
            } catch (Exception e) {
                // TODO: handle exception
                _log.error("文件上传失败!"+e.getMessage());
                result = new BaseResult(BaseResultCode.EXCEPTION, "上传失败");
            }
        } else {
            _log.error("不允许上传空文件");
            result = new BaseResult(BaseResultCode.EXCEPTION, "上传失败,因为文件是空的");
        }
        return result;
    }
 
Example 10
Source File: UploadController.java    From spring-boot-projects with Apache License 2.0 5 votes vote down vote up
@PostMapping({"/upload/file"})
@ResponseBody
public Result upload(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
    if (file.isEmpty()) {
        return ResultGenerator.genFailResult("请选择文件");
    }
    String fileName = file.getOriginalFilename();
    String suffixName = fileName.substring(fileName.lastIndexOf("."));
    //生成文件名称通用方法
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
    Random r = new Random();
    StringBuilder tempName = new StringBuilder();
    tempName.append(sdf.format(new Date())).append(r.nextInt(100)).append(suffixName);
    String newFileName = tempName.toString();
    try {
        // 保存文件
        byte[] bytes = file.getBytes();
        Path path = Paths.get(Constants.FILE_UPLOAD_PATH + newFileName);
        Files.write(path, bytes);

    } catch (IOException e) {
        e.printStackTrace();
    }
    Result result = ResultGenerator.genSuccessResult();
    result.setData("/files/" + newFileName);
    return result;
}
 
Example 11
Source File: UploadFileController.java    From spring-boot with Apache License 2.0 5 votes vote down vote up
/**
     * 文件上传
     * <p/>
     * spring boot 的配置文件 application.properties 中可以配置
     * spring.servlet.multipart.  可以配置上传文件属性
     *
     * @param file
     * @return
     */
//    <form method="POST" enctype="multipart/form-data" action="/files/upload">
//    File to upload:  <input type="file" name="file">
//    <br />
//    <br />
//    <input type="submit" value="Upload">
//    Press here to upload the file!
//    </form>
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    @ResponseBody
    public String handleFileUpload(@RequestParam("file") MultipartFile file) {
        if (file != null && !file.isEmpty()) {
            try {

                String fileName = file.getOriginalFilename();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
                //文件存放路径为 webApp/upload
                FileOutputStream fos = new FileOutputStream(servletContext.getRealPath("/") +
                        "upload/" + sdf.format(new Date()) + fileName.substring(fileName.lastIndexOf('.')));
                FileCopyUtils.copy(file.getInputStream(), fos);
                log.info("save to db");
                return "You successfully uploaded " + fileName + "!";
            } catch (Exception e) {
                return "You failed to upload " + e.getMessage();
            }
        } else {
            return "You failed to upload because the file was empty.";
        }
    }
 
Example 12
Source File: SysProfileController.java    From supplierShop with MIT License 5 votes vote down vote up
/**
 * 保存头像
 */
@Log(title = "个人信息", businessType = BusinessType.UPDATE)
@PostMapping("/updateAvatar")
@ResponseBody
public AjaxResult updateAvatar(@RequestParam("avatarfile") MultipartFile file)
{
    SysUser currentUser = ShiroUtils.getSysUser();
    try
    {
        if (!file.isEmpty())
        {
            String avatar = FileUploadUtils.upload(Global.getAvatarPath(), file);
            currentUser.setAvatar(avatar);
            if (userService.updateUserInfo(currentUser) > 0)
            {
                ShiroUtils.setSysUser(userService.selectUserById(currentUser.getUserId()));
                return success();
            }
        }
        return error();
    }
    catch (Exception e)
    {
        log.error("修改头像失败!", e);
        return error(e.getMessage());
    }
}
 
Example 13
Source File: FileUtils.java    From mogu_blog_v2 with Apache License 2.0 5 votes vote down vote up
/**
 * 上传文件
 *
 * @param pathRoot 物理路径webapp所在路径
 * @return 返回图片上传的地址
 * @throws IOException
 * @throws IllegalStateException
 */
public static String uploadFile(String pathRoot, String baseUrl, MultipartFile avatar) throws IllegalStateException, IOException {
    String path = "";
    if (!avatar.isEmpty()) {
        //获得文件类型(可以判断如果不是图片,禁止上传)  
        String contentType = avatar.getContentType();
        if (contentType.indexOf("image") != -1) {
            //获得文件后缀名称
            String imageName = contentType.substring(contentType.indexOf("/") + 1);
            path = baseUrl + StrUtils.getUUID() + "." + imageName;
            avatar.transferTo(new File(pathRoot + path));
        }
    }
    return path;
}
 
Example 14
Source File: StorageServiceImpl.java    From itweet-boot with Apache License 2.0 5 votes vote down vote up
private void storeFile(MultipartFile file, String filename, String ruleFilename, Path rootLocation) throws SystemException {
    try {
        if (file.isEmpty()) {
            throw  new SystemException("Failed to store empty file " + filename);
        }
        Files.copy(file.getInputStream(), rootLocation.resolve(ruleFilename));
    } catch (IOException e) {
        throw new SystemException("Failed to store file " + filename, e);
    }
}
 
Example 15
Source File: BinaryUploader.java    From kvf-admin with MIT License 4 votes vote down vote up
protected State doSave(MultipartRequest request, Map<String, Object> conf) {
    Map<String, MultipartFile> map = request.getFileMap();

    try {
        MultipartFile file = null;
        for (MultipartFile temp : map.values()) {
            if (!temp.isEmpty()) {
                file = temp;
                break;
            }
        }

        if (file == null) {
            return new BaseState(false, AppInfo.NOTFOUND_UPLOAD_DATA);
        }

        String savePath = (String) conf.get("savePath");
        String originFileName = file.getOriginalFilename();
        String suffix = FileType.getSuffixByFilename(originFileName);

        originFileName = originFileName.substring(0, originFileName.length() - suffix.length());
        savePath = savePath + suffix;

        long maxSize = ((Long) conf.get("maxSize")).longValue();

        if (!validType(suffix, (String[]) conf.get("allowFiles"))) {
            return new BaseState(false, AppInfo.NOT_ALLOW_FILE_TYPE);
        }

        savePath = PathFormat.parse(savePath, originFileName);

        String rootPath = (String) conf.get("rootPath");

        InputStream is = file.getInputStream();
        State storageState = storage.saveFileByInputStream(is, rootPath, savePath, maxSize);
        is.close();

        if (storageState.isSuccess()) {
            storageState.putInfo("type", suffix);
            storageState.putInfo("original", originFileName + suffix);
        }

        return storageState;
    } catch (IOException e) {
        return new BaseState(false, AppInfo.IO_ERROR);
    }
}
 
Example 16
Source File: AttachmentController.java    From SENS with GNU General Public License v3.0 4 votes vote down vote up
public Map<String, Object> uploadAttachment(@RequestParam("file") MultipartFile file,
                                            HttpServletRequest request) {

    Long userId = getLoginUserId();
    final Map<String, Object> result = new HashMap<>(3);
    if (!file.isEmpty()) {
        try {
            final Map<String, String> resultMap = attachmentService.upload(file, request);
            if (resultMap == null || resultMap.isEmpty()) {
                log.error("File upload failed");
                result.put("success", ResultCodeEnum.FAIL.getCode());
                result.put("message", localeMessageUtil.getMessage("code.admin.attachment.upload-failed"));
                return result;
            }
            //保存在数据库
            Attachment attachment = new Attachment();
            attachment.setUserId(userId);
            attachment.setAttachName(resultMap.get("fileName"));
            attachment.setAttachPath(resultMap.get("filePath"));
            attachment.setAttachSmallPath(resultMap.get("smallPath"));
            attachment.setAttachType(file.getContentType());
            attachment.setAttachSuffix(resultMap.get("suffix"));
            attachment.setCreateTime(DateUtil.date());
            attachment.setAttachSize(resultMap.get("size"));
            attachment.setAttachWh(resultMap.get("wh"));
            attachment.setAttachLocation(resultMap.get("location"));
            attachmentService.insert(attachment);
            log.info("Upload file {} to {} successfully", resultMap.get("fileName"), resultMap.get("filePath"));
            result.put("success", ResultCodeEnum.SUCCESS.getCode());
            result.put("message", localeMessageUtil.getMessage("code.admin.attachment.upload-success"));
            result.put("url", attachment.getAttachPath());
            result.put("filename", resultMap.get("filePath"));
        } catch (Exception e) {
            log.error("Upload file failed:{}", e.getMessage());
            result.put("success", ResultCodeEnum.FAIL.getCode());
            result.put("message", localeMessageUtil.getMessage("code.admin.attachment.upload-failed"));
        }
    } else {
        log.error("File cannot be empty!");
    }
    return result;
}
 
Example 17
Source File: TemplateManageAction.java    From bbs with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * 模板管理 添加
 */
@RequestMapping(params="method=add", method=RequestMethod.POST)
public String add(ModelMap model,Templates formbean,BindingResult result, 
		MultipartHttpServletRequest request, HttpServletResponse response)throws Exception {
	
	//数据校验
	this.validator.validate(formbean, result); 
	
	Templates templates = new Templates();
	templates.setName(formbean.getName().trim());
	templates.setDirName(formbean.getDirName().trim());
	templates.setIntroduction(formbean.getIntroduction());
	
	
	if (!result.hasErrors()) {  
		//图片上传
		List<MultipartFile> files = request.getFiles("uploadImage"); 
		for(MultipartFile file : files) {
			if(!file.isEmpty()){	
				//验证文件类型
				List<String> formatList = new ArrayList<String>();
				formatList.add("gif");
				formatList.add("jpg");
				formatList.add("jpeg");
				formatList.add("bmp");
				formatList.add("png");
				boolean authentication = FileUtil.validateFileSuffix(file.getOriginalFilename(),formatList);
				if(authentication){
					//取得文件后缀		
					String ext = FileUtil.getExtension(file.getOriginalFilename());
					//文件保存目录
					String pathDir = "common"+File.separator+formbean.getDirName()+File.separator;
					//构建文件名称
					String fileName = "templates." + ext;
					templates.setThumbnailSuffix(ext);
					
					//生成文件保存目录
					FileUtil.createFolder(pathDir);
					//保存文件
					localFileManage.writeFile(pathDir, fileName,file.getBytes());
			   }else{
				   result.rejectValue("thumbnailSuffix","errors.required", new String[]{"图片格式错误"},"");
			   }
			}
			
			break;//只有一个文件上传框
		}
	}

	if (result.hasErrors()) {  
		return "jsp/template/add_templates";
	} 
	
	
	
	List<Layout> layoutList = templateManage.newTemplate(templates.getDirName());
	templateService.saveTemplate(templates,layoutList);
	
	model.addAttribute("message","添加模板成功");//返回消息
	model.addAttribute("urladdress", RedirectPath.readUrl("control.template.list"));//返回消息//返回转向地址
	return "jsp/common/message";
}
 
Example 18
Source File: AttachmentController.java    From blog-sharon with Apache License 2.0 4 votes vote down vote up
/**
 * 上传附件
 *
 * @param file    file
 * @param request request
 * @return Map
 */
@PostMapping(value = "/upload", produces = {"application/json;charset=UTF-8"})
@ResponseBody
public Map<String, Object> upload(@RequestParam("file") MultipartFile file,
                                  HttpServletRequest request) {
    Map<String, Object> result = new HashMap<>(3);
    if (!file.isEmpty()) {
        try {
            Map<String, String> resultMap = attachmentService.upload(file, request);
            if (resultMap == null || resultMap.isEmpty()) {
                log.error("File upload failed");
                result.put("success", ResultCodeEnum.FAIL.getCode());
                result.put("message", localeMessageUtil.getMessage("code.admin.attachment.upload-failed"));
                return result;
            }
            //保存在数据库
            Attachment attachment = new Attachment();
            attachment.setAttachName(resultMap.get("fileName"));
            attachment.setAttachPath(resultMap.get("filePath"));
            attachment.setAttachSmallPath(resultMap.get("smallPath"));
            attachment.setAttachType(file.getContentType());
            attachment.setAttachSuffix(resultMap.get("suffix"));
            attachment.setAttachCreated(DateUtil.date());
            attachment.setAttachSize(resultMap.get("size"));
            attachment.setAttachWh(resultMap.get("wh"));
            attachment.setAttachLocation(resultMap.get("location"));
            attachmentService.save(attachment);
            log.info("Upload file {} to {} successfully", resultMap.get("fileName"), resultMap.get("filePath"));
            result.put("success", ResultCodeEnum.SUCCESS.getCode());
            result.put("message", localeMessageUtil.getMessage("code.admin.attachment.upload-success"));
            result.put("url", attachment.getAttachPath());
            result.put("filename", resultMap.get("filePath"));
            logsService.save(LogsRecord.UPLOAD_FILE, resultMap.get("fileName"), request);
        } catch (Exception e) {
            log.error("Upload file failed:{}", e.getMessage());
            result.put("success", ResultCodeEnum.FAIL.getCode());
            result.put("message", localeMessageUtil.getMessage("code.admin.attachment.upload-failed"));
        }
    } else {
        log.error("File cannot be empty!");
    }
    return result;
}
 
Example 19
Source File: CommentManageAction.java    From bbs with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * 评论  图片上传
 * 
 * 员工发话题 上传文件名为UUID + a + 员工Id
 * 用户发话题 上传文件名为UUID + b + 用户Id
 * @param topicId 话题Id
 * @param userName 用户名称
 * @param isStaff 是否是员工   true:员工   false:会员
 */
@RequestMapping(params="method=uploadImage",method=RequestMethod.POST)
@ResponseBody//方式来做ajax,直接返回字符串
public String uploadImage(ModelMap model,Long topicId,String userName, Boolean isStaff,
		MultipartFile imgFile, HttpServletResponse response) throws Exception {
	
	String number = topicManage.generateFileNumber(userName, isStaff);
	
	Map<String,Object> returnJson = new HashMap<String,Object>();
	
	//文件上传
	if(imgFile != null && !imgFile.isEmpty() && topicId != null && topicId >0L && number != null && !"".equals(number.trim())){
		EditorTag editorSiteObject = settingManage.readEditorTag();
		if(editorSiteObject != null){
			if(editorSiteObject.isImage()){//允许上传图片
				//当前图片文件名称
				String fileName = imgFile.getOriginalFilename();
				//文件大小
				Long size = imgFile.getSize();
				//取得文件后缀
				String suffix = fileName.substring(fileName.lastIndexOf('.')+1).toLowerCase();
				
				
				//允许上传图片格式
				List<String> imageFormat = editorSiteObject.getImageFormat();
				//允许上传图片大小
				long imageSize = editorSiteObject.getImageSize();

				//验证文件类型
				boolean authentication = FileUtil.validateFileSuffix(imgFile.getOriginalFilename(),imageFormat);
				
				if(authentication && size/1024 <= imageSize){
					
					//文件保存目录;分多目录主要是为了分散图片目录,提高检索速度
					String pathDir = "file"+File.separator+"comment"+File.separator + topicId + File.separator;
					//文件锁目录
					String lockPathDir = "file"+File.separator+"comment"+File.separator+"lock"+File.separator;
					//构建文件名称
					String newFileName = UUIDUtil.getUUID32()+ number+"." + suffix;
					
					//生成文件保存目录
					fileManage.createFolder(pathDir);
					//生成锁文件保存目录
					fileManage.createFolder(lockPathDir);
					//生成锁文件
					fileManage.addLock(lockPathDir,topicId+"_"+newFileName);
					//保存文件
					fileManage.writeFile(pathDir, newFileName,imgFile.getBytes());
	
					//上传成功
					returnJson.put("error", 0);//0成功  1错误
					returnJson.put("url", "file/comment/"+topicId+"/"+newFileName);
					
					return JsonUtils.toJSONString(returnJson);
				}
			}
		}
		
	}
	
	//上传失败
	returnJson.put("error", 1);
	returnJson.put("message", "上传失败");
	return JsonUtils.toJSONString(returnJson);
}
 
Example 20
Source File: FilterWordManageAction.java    From bbs with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * 上传词库
 */
@RequestMapping(params="method=uploadFilterWord",method=RequestMethod.POST)
@ResponseBody//方式来做ajax,直接返回字符串
public String uploadFilterWord(ModelMap model,
		MultipartHttpServletRequest request) throws Exception {
	Map<String,Object> returnJson = new HashMap<String,Object>();
	Map<String,String> error = new HashMap<String,String>();

	FileOutputStream fileoutstream = null;
	try {
		//获得文件: 
		MultipartFile file = request.getFile("file");
		if(file != null && !file.isEmpty()){
			//验证文件后缀
			List<String> flashFormatList = new ArrayList<String>();
			flashFormatList.add("txt");
			boolean authentication = FileUtil.validateFileSuffix(file.getOriginalFilename(),flashFormatList);
			if(authentication){
				
				//文件保存目录
				String pathDir = "WEB-INF"+File.separator+"data"+File.separator+"filterWord"+File.separator;
				//生成文件保存目录
				FileUtil.createFolder(pathDir);
				//保存文件
				localFileManage.writeFile(pathDir, "word.txt",file.getBytes());
				
			}else{
				error.put("file", "文件格式错误");
			}
		}else{
			error.put("file", "请选择文件");
		}
		
	
		
	} catch (Exception e) {
		error.put("file", "上传错误");
	//	e.printStackTrace();
	}finally{
		if(fileoutstream != null){
			fileoutstream.close();
		}
	}
	
	if(error.size() >0){
		//上传失败
		returnJson.put("error", error);
		returnJson.put("success", false);
	}else{
		returnJson.put("success", true);
	}
	
	return JsonUtils.toJSONString(returnJson);
	

}