Java 类org.springframework.web.multipart.commons.CommonsMultipartFile 实例源码

项目:classchecks    文件:ClockinAsStudentController.java   
/**
 * 
* @Title: doClockIn 
* @Description: 学生在教师拍照考勤时,没有检测到自己考勤
* @return
* BasicEntityVo<?>
 */
@RequestMapping("/clock-in")
@ResponseBody
public BasicEntityVo<?> doClockIn(String jwAccount, String loginAccount, 
        Double lng, Double lat, @RequestParam("clockinImg")CommonsMultipartFile file) {
    if(StringUtils.isBlank(jwAccount)) {
        return new BasicEntityVo<>(StudentClockInBusinessCode.JW_ACCOUNT_EMPTY[0], StudentClockInBusinessCode.JW_ACCOUNT_EMPTY[1]);
    }
    if(StringUtils.isBlank(loginAccount)) {
        return new BasicEntityVo<>(StudentClockInBusinessCode.LOGIN_ACCOUNT_EMPTY[0], StudentClockInBusinessCode.LOGIN_ACCOUNT_EMPTY[1]);
    }
    if(lng == 0.0 || null == lng || lat == 0.0 || null == lat) {
        return new BasicEntityVo<>(StudentClockInBusinessCode.LNG_LAT_EMPTY[0], StudentClockInBusinessCode.LNG_LAT_EMPTY[1]);
    }
    if(file.isEmpty()) {
        return new BasicEntityVo<>(StudentClockInBusinessCode.BUSSINESS_IMAGE_EMPTY[0], StudentClockInBusinessCode.BUSSINESS_IMAGE_EMPTY[1]);
    }

    return clockinAsStudentService.clockin(jwAccount, loginAccount, lng, lat, file);
}
项目:communote-server    文件:UserProfileActionController.java   
/**
 * Upload an image using AJAX. The response will be returned as JSON object.
 *
 * @param request
 *            the servlet request
 * @param userId
 *            the ID of the user whose image will be updated
 * @return the JSON response object
 */
private ObjectNode doUploadImageAjax(HttpServletRequest request, Long userId) {

    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
    CommonsMultipartFile cFile = (CommonsMultipartFile) multipartRequest.getFile("file");
    String errorMessage = null;
    if (cFile != null && cFile.getSize() > 0) {
        if (cFile.getSize() < getMaxUploadSize()) {
            errorMessage = storeImage(request, cFile, userId);
        } else {
            errorMessage = MessageHelper.getText(request, "user.profile.upload.filesize.error",
                    new Object[] { FileUtils.byteCountToDisplaySize(getMaxUploadSize()) });
        }
    } else {
        errorMessage = MessageHelper.getText(request, "user.profile.upload.empty.image");
    }
    if (errorMessage != null) {
        return JsonRequestHelper.createJsonErrorResponse(errorMessage);
    }
    return JsonRequestHelper.createJsonSuccessResponse(null, createSuccessResult(userId));
}
项目:iVIS    文件:ActivityRestControllerImpl.java   
@RequestMapping(value = "/attach/{id}", method = RequestMethod.POST)
public String setAttachment(@PathVariable("id") Long activityId,
                          @RequestParam("file") CommonsMultipartFile attachment,
                          WebRequest webRequest) {
    IssueAttachmentFileUtil issueAttachmentFileUtil = new IssueAttachmentFileUtil();

    Activity activity = activityService.find(activityId);

    issueAttachmentFileUtil.deleteIfExcist(activity, servletContext);

    activity.setFileName(attachment.getOriginalFilename());
    activity = activityService.save(activity);

    if (!attachment.isEmpty() && activity != null) {

        issueAttachmentFileUtil.saveActivityAttachment(activity, attachment, servletContext);
    }

    return activity.getFileName();
}
项目:iVIS    文件:SchemaVersionController.java   
@RequestMapping(method = RequestMethod.POST)
public ModelAndView migrate(@RequestParam("file") CommonsMultipartFile multipartFile,
                            @RequestParam(value = "description", required = false) String description,
                            WebRequest webRequest) {

    SchemaVersion currentVersion = createCurrentVersion(multipartFile.getOriginalFilename(), description);

    DatabaseWorker databaseWorker = new DatabaseWorker(dataSource, currentVersion, servletContext);

    if (!databaseWorker.runScript(multipartFile)) {
        schemeVersionService.delete(currentVersion.getId());
    } else {
        databaseWorker.createVersionDump();
    }

    return new ModelAndView("redirect:/test.html");
}
项目:putnami-web-toolkit    文件:FileTransfertController.java   
@RequestMapping(value = "/file/upload/{uploadId}", method = RequestMethod.POST)
@ResponseBody
public FileDto upload(@PathVariable String uploadId,
    @RequestParam("data") CommonsMultipartFile multipart, HttpServletRequest request,
    HttpServletResponse response) {
    OutputStream out = null;
    InputStream in = null;
    try {
        out = this.store.write(uploadId, multipart.getOriginalFilename(), multipart.getContentType());
        in = multipart.getInputStream();
        IOUtils.copy(in, out);
        return this.store.getFileBean(uploadId);
    } catch (IOException e) {
        throw new RuntimeException(e.getMessage(), e);
    } finally {
        IOUtils.closeQuietly(in);
        IOUtils.closeQuietly(out);
    }
}
项目:Fancraft    文件:S3DAO.java   
public String storeFile(CommonsMultipartFile file, String userId,
        String postTimestamp) {
    try {

        ObjectMetadata omd = new ObjectMetadata();
        omd.setContentType("application/octet-stream");
        omd.addUserMetadata("originalfilename", file.getOriginalFilename());

        String path = "files/" + userId + "_" + postTimestamp.replace(':', '_') + "_" + file.getOriginalFilename();

        PutObjectRequest request = new PutObjectRequest(BUCKET_NAME,
                path,
                file.getInputStream(), omd);

        s3client.putObject(request);

        s3client.setObjectAcl(BUCKET_NAME, path, CannedAccessControlList.PublicRead);

        return "http://s3.amazonaws.com/" + BUCKET_NAME + "/" + path;
    } catch (IOException e) {
        return null;
    }

}
项目:Fancraft    文件:S3DAO.java   
public String storePicture(CommonsMultipartFile file, String userId,
        String postTimestamp) {
    try {

        ObjectMetadata omd = new ObjectMetadata();
        omd.setContentType("application/octet-stream");
        omd.addUserMetadata("originalfilename", file.getOriginalFilename());

        String path = "pictures/" + userId + "_" + postTimestamp.replace(':', '_') + "_" + file.getOriginalFilename();

        PutObjectRequest request = new PutObjectRequest(BUCKET_NAME,
                path,
                file.getInputStream(), omd);

        s3client.putObject(request);

        s3client.setObjectAcl(BUCKET_NAME, path, CannedAccessControlList.PublicRead);

        return "http://s3.amazonaws.com/" + BUCKET_NAME + "/" + path;
    } catch (IOException e) {
        return null;
    }

}
项目:Tanaguru    文件:UploadAuditSetUpCommandHelper.java   
/**
 * This method converts the uploaded files into a map where the key is the
 * file name and the value is the file content.
 */
public synchronized  static Map<String, String> convertFilesToMap(CommonsMultipartFile[] fileInputList ) {
    Map<String, String> fileMap = new LinkedHashMap<String, String>();
    CommonsMultipartFile tmpMultiFile;
    String tmpCharset;
    fileNameCounterMap.clear();
    for (int i = 0; i < fileInputList.length; i++) {
        tmpMultiFile = fileInputList[i];
        try {
            if (tmpMultiFile != null && !tmpMultiFile.isEmpty() && tmpMultiFile.getInputStream() != null) {
                tmpCharset = CrawlUtils.extractCharset(tmpMultiFile.getInputStream());
                fileMap.put(
                        getFileName(tmpMultiFile.getOriginalFilename()),
                        tmpMultiFile.getFileItem().getString(tmpCharset));
            }
        } catch (IOException e) {}
    }
    return fileMap;
}
项目:NEILREN4J    文件:IPDBService.java   
public String saveFile(CommonsMultipartFile file) throws IOException {
    String filePath = "/tmp/neilren4j_ip_" + new Date().getTime() + file.getOriginalFilename();
    File newFile = new File(filePath);
    //通过CommonsMultipartFile的方法直接写文件(注意这个时候)
    file.transferTo(newFile);
    return filePath;
}
项目:classchecks    文件:RegisterServiceImpl.java   
@Override
    @Transactional(readOnly = false, rollbackFor = RuntimeException.class)
    public BasicVo register(String phone, String smscode, String regID, CommonsMultipartFile[] files) {
        // 检测数据库是否已有记录,这里检查是防止用户获取验证码成功后,更换一个已有的手机号输入
        boolean hasPhone = smsCodeMapper.hasPhoneRegistered(phone).length > 0 ? true : false;
        if(hasPhone) {
            return new BasicVo(RegisterBusinessCode.BUSSINESS_PHONE_EXIST[0], RegisterBusinessCode.BUSSINESS_PHONE_EXIST[1]);
        }

        // 调用短信接口验证输入的短信验证码是否可用
        boolean isVerify = SMSUtil.verifySmsCode(phone, smscode);

        if(isVerify) {
            BasicVo basicVo = null;
            try {
                SecurityAccountVo secAcc = new SecurityAccountVo();
                secAcc.setSecurityAccount(phone);
                secAcc.setSecuritSmsCode(smscode);
                secAcc.setRegID(regID);
                secAcc.setSecuritType(Student_User_Type);
//              // 插入数据
                registerMapper.saveRegisterInfo(secAcc);
                secAcc = registerMapper.findAccountByPhone(phone);
                LOG.info("secAcc="+secAcc);
                fileSave(files, phone); // 保存上传的图片到临时位置
                // 图片预处理
                rawFaceProc(ImgStoragePath.RAW_FACE_IMG_SAVE_PATH+File.separator+phone,
                        ImgStoragePath.PROC_FACE_IMG_SAVE_PATH+File.separator+phone, secAcc.getFaceLabel());
                // 生成CSV标签
                generateCSV(ImgStoragePath.PROC_FACE_IMG_SAVE_PATH+File.separator+phone, ImgStoragePath.CSV_FILE_SAVE_PATH);
                basicVo = new BasicVo(RegisterBusinessCode.BUSINESS_SUCCESS[0], RegisterBusinessCode.BUSINESS_SUCCESS[1]);
            } catch(Exception e) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                basicVo = new BasicVo(RegisterBusinessCode.BUSSINESS_FAILED[0], RegisterBusinessCode.BUSSINESS_FAILED[1]);
                LOG.error("学生注册错误", e);
            }
            return basicVo;
        }
        return new BasicVo(RegisterBusinessCode.BUSSINESS_SMS_ERROR[0], RegisterBusinessCode.BUSSINESS_SMS_ERROR[1]);
    }
项目:helium    文件:TascaTramitacioController.java   
@RequestMapping(value = "/{tascaId}/document/{documentCodi}/adjuntar", method = RequestMethod.POST)
public String documentAdjuntar(
        HttpServletRequest request,
        @PathVariable String tascaId,
        @PathVariable String documentCodi,
        @RequestParam(value = "arxiu", required = false) final CommonsMultipartFile arxiu,  
        @RequestParam(value = "data", required = false) Date data,
        Model model) {
    try {
        byte[] contingutArxiu = IOUtils.toByteArray(arxiu.getInputStream());
        String nomArxiu = arxiu.getOriginalFilename();
        ExpedientTascaDto tasca = tascaService.findAmbIdPerTramitacio(tascaId);
        if (!tasca.isValidada()) {
            MissatgesHelper.error(request, getMessage(request, "error.validar.dades"));
        } else if (!expedientService.isExtensioDocumentPermesa(nomArxiu)) {
            MissatgesHelper.error(request, getMessage(request, "error.extensio.document"));
        } else if (nomArxiu.isEmpty() || contingutArxiu.length == 0) {
            MissatgesHelper.error(request, getMessage(request, "error.especificar.document"));
        } else {
            accioDocumentAdjuntar(
                    request,
                    tascaId,
                    documentCodi,
                    nomArxiu,
                    contingutArxiu,
                    (data == null) ? new Date() : data).toString();
        }
    } catch (Exception ex) {
        MissatgesHelper.error(request, getMessage(request, "error.guardar.document") + ": " + ex.getLocalizedMessage());
        logger.error("Error al adjuntar el document a la tasca(" +
                "tascaId=" + tascaId + ", " +
                "documentCodi=" + documentCodi + ")",
                ex);
    }
    return mostrarInformacioTascaPerPipelles(
            request,
            tascaId,
            model,
            "document");
}
项目:helium    文件:ExpedientDocumentController.java   
@RequestMapping(value="/{expedientId}/documentAdjuntar", method = RequestMethod.POST)
public String documentModificarPost(
        HttpServletRequest request,
        @PathVariable Long expedientId,
        @RequestParam(value = "accio", required = true) String accio,
        @ModelAttribute DocumentExpedientCommand command, 
        @RequestParam(value = "arxiu", required = false) final CommonsMultipartFile arxiu,  
        @RequestParam(value = "processInstanceId", required = true) String processInstanceId,
        BindingResult result, 
        SessionStatus status, 
        Model model) {
    try {
        new DocumentModificarValidator().validate(command, result);
        if (result.hasErrors() || arxiu == null || arxiu.isEmpty()) {
            if (arxiu == null || arxiu.isEmpty()) {
                MissatgesHelper.error(request, getMessage(request, "error.especificar.document"));                          
            }
            model.addAttribute("processInstanceId", processInstanceId);
            return "v3/expedientDocumentNou";
        }

        byte[] contingutArxiu = IOUtils.toByteArray(arxiu.getInputStream());
        String nomArxiu = arxiu.getOriginalFilename();
        command.setNomArxiu(nomArxiu);
        command.setContingut(contingutArxiu);

        expedientService.crearModificarDocument(expedientId, processInstanceId, null, command.getNom(), command.getNomArxiu(), command.getDocId(), command.getContingut(), command.getData());
        MissatgesHelper.success(request, getMessage(request, "info.document.guardat") );
       } catch (Exception ex) {
        logger.error("No s'ha pogut crear el document: expedientId: " + expedientId, ex);
        MissatgesHelper.error(request, getMessage(request, "error.proces.peticio") + ": " + ex.getLocalizedMessage());
       }
    return modalUrlTancar(false);
}
项目:communote-server    文件:ClientProfileController.java   
/**
 * Handle upload client logo.
 *
 * @param request
 *            the request
 * @param errors
 *            the errors
 * @param form
 *            the form backing object
 * @return the model and view
 */
private ModelAndView handleUploadClientLogo(HttpServletRequest request, BindException errors,
        ClientProfileLogoForm form) {
    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
    CommonsMultipartFile cFile = (CommonsMultipartFile) multipartRequest.getFile("file");
    if (cFile == null || cFile.getSize() <= 0) {
        MessageHelper.saveErrorMessageFromKey(request,
                "client.change.logo.image.upload.empty.image");
        return null;
    }
    ModelAndView mav = null;
    long maxUploadSize = Long.parseLong(CommunoteRuntime.getInstance()
            .getConfigurationManager().getApplicationConfigurationProperties()
            .getProperty(ApplicationProperty.IMAGE_MAX_UPLOAD_SIZE));
    if (cFile.getSize() < maxUploadSize) {
        try {
            byte[] dataLarge = cFile.getBytes();
            ServiceLocator.instance().getService(ConfigurationManagement.class)
                    .updateClientLogo(dataLarge);
            MessageHelper
                    .saveMessageFromKey(request, "client.change.logo.image.upload.success");
            ServiceLocator.findService(ImageManager.class).imageChanged(
                    ClientImageDescriptor.IMAGE_TYPE_NAME,
                    ClientImageProvider.PROVIDER_IDENTIFIER, ClientHelper.getCurrentClientId());
            form.setCustomClientLogo(true);
            mav = new ModelAndView(getSuccessView(), getCommandName(), form);
        } catch (Exception e) {
            LOGGER.error("image upload failed", e);
            String errorMsgKey = getImageUploadExceptionErrorMessageKey(e);
            MessageHelper
                    .saveErrorMessage(request, MessageHelper.getText(request, errorMsgKey));
        }
    } else {
        MessageHelper.saveErrorMessageFromKey(request,
                "client.change.logo.image.upload.filesize.error");
    }
    return mav;
}
项目:imageweb    文件:FileUtil.java   
public static File multipartFile2File(MultipartFile file) {
    CommonsMultipartFile commonsMultipartFile = (CommonsMultipartFile) file;
    DiskFileItem fileItem = (DiskFileItem) commonsMultipartFile.getFileItem();

    File _file = fileItem.getStoreLocation();
    return _file;
}
项目:hotel_shop    文件:DocumentsController.java   
/**
 * Upload image.
 *
 * @param file the file
 * @param principal the principal
 * @return the map< string,? extends object>
 */
@RequestMapping(value = "/document/upload", method = RequestMethod.POST)
public @ResponseBody Map<String, ? extends Object> uploadImage(@RequestParam("file") CommonsMultipartFile file
        , Principal principal) {

    SasUser sasUser = JsonOutput.readSasUser(principal);

    if (!file.isEmpty()) {
        if (debug) {
            System.out.println(
                    "file: " + file + 
                    ", name: " + file.getName() +
                    ", contentType: " + file.getContentType() +
                    ", originalFilename: " + file.getOriginalFilename() +
                    ", extension: " + FilenameUtils.getExtension(file.getOriginalFilename()) +
                    ", size: " + file.getSize() +
                    ", defaultpath: " + filesSettings.getDocumentsDefaultPath()
            );
        }

        try {
            byte[] bytes = file.getBytes();


            return JsonOutput.mapSuccess();
        } catch (Exception e) {
            return JsonOutput.mapError( "Failed to upload " + file.getOriginalFilename() + " => " + e.getMessage() );
        }
    } else {
        return JsonOutput.mapError( "You failed to upload " + file.getOriginalFilename() + " because the file was empty." );
    }
}
项目:amediamanager    文件:DynamoDbUserDaoImpl.java   
/**
   * Upload the profile pic to S3 and return it's URL
   * @param profilePic
   * @return The fully-qualified URL of the photo in S3
   * @throws IOException
   */
  public String uploadFileToS3(CommonsMultipartFile profilePic) throws IOException {

// Profile pic prefix
    String prefix = config.getProperty(ConfigProps.S3_PROFILE_PIC_PREFIX);

// Date string
String dateString = new SimpleDateFormat("ddMMyyyy").format(new java.util.Date());
String s3Key = prefix + "/" + dateString + "/" + UUID.randomUUID().toString() + "_" + profilePic.getOriginalFilename();

// Get bucket
String s3bucket = config.getProperty(ConfigProps.S3_UPLOAD_BUCKET);

// Create a ObjectMetadata instance to set the ACL, content type and length
ObjectMetadata metadata = new ObjectMetadata();
metadata.setContentType(profilePic.getContentType());
metadata.setContentLength(profilePic.getSize());

// Create a PutRequest to upload the image
PutObjectRequest putObject = new PutObjectRequest(s3bucket, s3Key, profilePic.getInputStream(), metadata);

// Put the image into S3
s3Client.putObject(putObject);
s3Client.setObjectAcl(s3bucket, s3Key, CannedAccessControlList.PublicRead);

return "http://" + s3bucket + ".s3.amazonaws.com/" + s3Key;
  }
项目:Spring-Blog-Cms    文件:PostController.java   
@RequestMapping(value = "/postwrite", method = RequestMethod.POST)
public String doAddPost( HttpServletRequest request,
                        @ModelAttribute("post") Post post, @RequestParam CommonsMultipartFile[] imageName,
                        Principal principal) {

    // saveDirectory =  new File(".").getCanonicalPath();  retunt location C://tomcat-8/bin

    String saveDirectory = context.getRealPath("/resources/img/postImages");

    System.out.println("total file:"+ imageName.length);

    try {
        if (imageName != null && imageName.length > 0) {
            for (CommonsMultipartFile aFile : imageName){
                String filename = UUID.randomUUID().toString() + aFile.getOriginalFilename();
                post.setBannerImageName(filename);
                if (!aFile.getOriginalFilename().equals("")) {
                    aFile.transferTo(new File(saveDirectory+"/" + filename));
                }
            }
        }
    }
    catch (Exception ex) {
        ex.printStackTrace();
    }

    String name = principal.getName();
    postService.save(post, name);
    return "redirect:/index.html";
}
项目:modinvreg    文件:BaseController.java   
protected void sendSupportEmail( String fromEmail, String subject, String templateName, Map<String, Object> model,
        CommonsMultipartFile attachFile ) {
    SimpleMailMessage mailMessage = new SimpleMailMessage();
    // mailMessage.setTo( Settings.getAdminEmailAddress() );
    mailMessage.setFrom( Settings.getAdminEmailAddress() );
    mailMessage.setSubject( subject );
    mailMessage.setTo( Settings.getAdminEmailAddress() );
    mailEngine.sendMessage( mailMessage, templateName, model, attachFile );
}
项目:modinvreg    文件:RegisterController.java   
@RequestMapping(value = "/contactSupport.html", method = RequestMethod.POST)
public String contactSupport( HttpServletRequest request,
        final @RequestParam(required = false ) CommonsMultipartFile attachFile) {
    try {

        String email = userManager.getCurrentUsername();

        log.info( email + " is attempting to contact support, check debug for more information" );

        // reads form input
        // final String email = request.getParameter("email");
        final String name = request.getParameter( "name" );
        final String message = request.getParameter( "message" );

        String userAgent = request.getHeader( "User-Agent" );

        log.debug( email );
        log.debug( name );
        log.debug( message );
        log.debug( userAgent );
        log.debug( attachFile );

        String templateName = "contactSupport.vm";

        Map<String, Object> model = new HashMap<>();

        model.put( "name", name );
        model.put( "email", email );
        model.put( "userAgent", userAgent );
        model.put( "message", message );
        model.put( "boolFile", attachFile != null && !attachFile.getOriginalFilename().equals( "" ) );

        sendSupportEmail( email, "Registry Help - Contact Support", templateName, model, attachFile );
        return "success";
    } catch ( Exception e ) {
        // throw e;
        return "error";
    }

}
项目:pubanywhere    文件:MaxSizeUploadValidator.java   
public boolean isValid(Object obj, ConstraintValidatorContext context) {
    CommonsMultipartFile file = (CommonsMultipartFile) obj;

    if (file != null) {
        if (file.getSize() > 2000000) {
            context.disableDefaultConstraintViolation();
            context.buildConstraintViolationWithTemplate(messageService.getMessageFromResource(request, "config.error.maxUploadSize")).addConstraintViolation();
            return false;
        }
    }

    return true;
}
项目:Tanaguru    文件:UploadAuditSetUpFormValidator.java   
/**
 * Control whether the uploaded files are of HTML type and whether their
 * size is under the maxFileSize limit.
 *
 * @param uploadAuditSetUpCommand
 * @param errors
 */
private void validateFiles(AuditSetUpCommand uploadAuditSetUpCommand, Errors errors) {
    boolean emptyFile = true;
    Metadata metadata = new Metadata();
    MimeTypes mimeTypes = TikaConfig.getDefaultConfig().getMimeRepository();
    String mime = null;

    for (int i=0;i<uploadAuditSetUpCommand.getFileInputList().length;i++ ) {
        try {
            CommonsMultipartFile cmf = uploadAuditSetUpCommand.getFileInputList()[i];
            if (cmf.getSize() > maxFileSize) {
                Long maxFileSizeInMega = maxFileSize / 1000000;
                String[] arg = {maxFileSizeInMega.toString()};
                errors.rejectValue(ID_INPUT_FILE_PREFIX + "[" + i + "]", FILE_SIZE_EXCEEDED_MSG_BUNDLE_KEY, arg, "{0}");
            }
            if (cmf.getSize() > 0) {
                emptyFile = false;
                mime = mimeTypes.detect(new BufferedInputStream(cmf.getInputStream()), metadata).toString();
                LOGGER.debug("mime  " + mime + "  " +cmf.getOriginalFilename());
                if (!authorizedMimeType.contains(mime)) {
                    errors.rejectValue(ID_INPUT_FILE_PREFIX + "[" + i + "]", NOT_HTML_MSG_BUNDLE_KEY);
                }
            }
        } catch (IOException ex) {
            LOGGER.warn(ex);
            errors.rejectValue(ID_INPUT_FILE_PREFIX + "[" + i + "]", NOT_HTML_MSG_BUNDLE_KEY);
        }
    }
    if(emptyFile) { // if no file is uploaded
        LOGGER.debug("emptyFiles");
        errors.rejectValue(GENERAL_ERROR_MSG_KEY,
                NO_FILE_UPLOADED_MSG_BUNDLE_KEY);
    }
}
项目:molgenis    文件:ImportWizardControllerTest.java   
@Test
public void testImportFile() throws IOException, URISyntaxException
{
    // set up the test
    HttpServletRequest request = mock(HttpServletRequest.class);
    File file = new File("/src/test/resources/example.xlsx");

    DiskFileItem fileItem = new DiskFileItem("file", "text/plain", false, file.getName(), (int) file.length(),
            file.getParentFile());
    fileItem.getOutputStream();
    MultipartFile multipartFile = new CommonsMultipartFile(fileItem);
    ArgumentCaptor<InputStream> streamCaptor = ArgumentCaptor.forClass(InputStream.class);
    when(fileStore.store(streamCaptor.capture(), eq("example.xlsx"))).thenReturn(file);
    when(fileRepositoryCollectionFactory.createFileRepositoryCollection(file)).thenReturn(repositoryCollection);
    when(importServiceFactory.getImportService(file.getName())).thenReturn(importService);
    ImportRun importRun = importRunFactory.create();
    importRun.setStartDate(date);
    importRun.setProgress(0);
    importRun.setStatus(ImportStatus.RUNNING.toString());
    importRun.setOwner("Harry");
    importRun.setNotify(false);
    when(importRunService.addImportRun(SecurityUtils.getCurrentUsername(), false)).thenReturn(importRun);

    // the actual test
    ResponseEntity<String> response = controller.importFile(request, multipartFile, null, null, "add", null);
    assertEquals(response.getStatusCode(), HttpStatus.CREATED);

    ArgumentCaptor<ImportJob> captor = ArgumentCaptor.forClass(ImportJob.class);
    verify(executorService, times(1)).execute(captor.capture());
}
项目:molgenis    文件:ImportWizardControllerTest.java   
@Test
public void testImportUpdateFile() throws IOException, URISyntaxException
{
    // set up the test
    HttpServletRequest request = mock(HttpServletRequest.class);
    File file = new File("/src/test/resources/example.xlsx");

    DiskFileItem fileItem = new DiskFileItem("file", "text/plain", false, file.getName(), (int) file.length(),
            file.getParentFile());
    fileItem.getOutputStream();
    MultipartFile multipartFile = new CommonsMultipartFile(fileItem);
    ArgumentCaptor<InputStream> streamCaptor = ArgumentCaptor.forClass(InputStream.class);
    when(fileStore.store(streamCaptor.capture(), eq("example.xlsx"))).thenReturn(file);
    when(fileRepositoryCollectionFactory.createFileRepositoryCollection(file)).thenReturn(repositoryCollection);
    when(importServiceFactory.getImportService(file.getName())).thenReturn(importService);
    ImportRun importRun = importRunFactory.create();
    importRun.setStartDate(date);
    importRun.setProgress(0);
    importRun.setStatus(ImportStatus.RUNNING.toString());
    importRun.setOwner("Harry");
    importRun.setNotify(false);
    when(importRunService.addImportRun(SecurityUtils.getCurrentUsername(), false)).thenReturn(importRun);

    // the actual test
    ResponseEntity<String> response = controller.importFile(request, multipartFile, null, null, "update", null);
    assertEquals(response.getStatusCode(), HttpStatus.CREATED);
    assertEquals(response.getHeaders().getContentType(), TEXT_PLAIN);

    ArgumentCaptor<ImportJob> captor = ArgumentCaptor.forClass(ImportJob.class);
    verify(executorService, times(1)).execute(captor.capture());
}
项目:molgenis    文件:ImportWizardControllerTest.java   
@Test
public void testImportIllegalUpdateModeFile() throws IOException, URISyntaxException
{
    // set up the test
    HttpServletRequest request = mock(HttpServletRequest.class);
    File file = new File("/src/test/resources/example.xlsx");

    DiskFileItem fileItem = new DiskFileItem("file", "text/plain", false, file.getName(), (int) file.length(),
            file.getParentFile());
    fileItem.getOutputStream();
    MultipartFile multipartFile = new CommonsMultipartFile(fileItem);
    ArgumentCaptor<InputStream> streamCaptor = ArgumentCaptor.forClass(InputStream.class);
    when(fileStore.store(streamCaptor.capture(), eq("example.xlsx"))).thenReturn(file);
    when(fileRepositoryCollectionFactory.createFileRepositoryCollection(file)).thenReturn(repositoryCollection);
    when(importServiceFactory.getImportService(file.getName())).thenReturn(importService);
    ImportRun importRun = importRunFactory.create();
    importRun.setStartDate(date);
    importRun.setProgress(0);
    importRun.setStatus(ImportStatus.RUNNING.toString());
    importRun.setOwner("Harry");
    importRun.setNotify(false);
    when(importRunService.addImportRun(SecurityUtils.getCurrentUsername(), false)).thenReturn(importRun);

    // the actual test
    ResponseEntity<String> response = controller.importFile(request, multipartFile, null, null, "addsss", null);
    assertEquals(response.getStatusCode(), HttpStatus.BAD_REQUEST);
    assertEquals(response.getHeaders().getContentType(), TEXT_PLAIN);

    ArgumentCaptor<ImportJob> captor = ArgumentCaptor.forClass(ImportJob.class);
    verify(executorService, times(0)).execute(captor.capture());
}
项目:classchecks    文件:ClockinAsTeacherServiceImpl.java   
private boolean fileSave(CommonsMultipartFile img, String savePath, String longTime) {
    return SaveImageUtils.saveImage(img, savePath, longTime+".jpg");
}
项目:classchecks    文件:ClockinAsStudentServiceImpl.java   
private boolean fileSave(CommonsMultipartFile img, String savePath, String longTime) {
    return SaveImageUtils.saveImage(img, savePath, longTime+".jpg");
}
项目:helium    文件:TascaTramitacioController.java   
@RequestMapping(value = "/{tascaId}/{tascaId2}/document/{documentCodi}/adjuntar", method = RequestMethod.POST)
public String documentAdjuntar2(
        HttpServletRequest request,
        @PathVariable String tascaId,
        @PathVariable String tascaId2,
        @PathVariable String documentCodi,
        @RequestParam(value = "arxiu", required = false) final CommonsMultipartFile arxiu,  
        @RequestParam(value = "data", required = false) Date data,
        Model model) {
    try {
        byte[] contingutArxiu = IOUtils.toByteArray(arxiu.getInputStream());
        String nomArxiu = arxiu.getOriginalFilename();
        ExpedientTascaDto tasca = tascaService.findAmbIdPerTramitacio(tascaId);
        if (!tasca.isValidada()) {
            MissatgesHelper.error(request, getMessage(request, "error.validar.dades"));
        } else if (!expedientService.isExtensioDocumentPermesa(nomArxiu)) {
            MissatgesHelper.error(request, getMessage(request, "error.extensio.document"));
        } else if (nomArxiu.isEmpty() || contingutArxiu.length == 0) {
            MissatgesHelper.error(request, getMessage(request, "error.especificar.document"));
        } else {
            accioDocumentAdjuntar(
                    request,
                    tascaId,
                    documentCodi,
                    nomArxiu,
                    contingutArxiu,
                    (data == null) ? new Date() : data).toString();
        }
    } catch (Exception ex) {
        MissatgesHelper.error(request, getMessage(request, "error.guardar.document") + ": " + ex.getLocalizedMessage());
        logger.error("Error al adjuntar el document a la tasca(" +
                "tascaId=" + tascaId + ", " +
                "documentCodi=" + documentCodi + ")",
                ex);
    }
    return mostrarInformacioTascaPerPipelles(
            request,
            tascaId,
            model,
            "document");
}
项目:helium    文件:ExpedientDocumentController.java   
@RequestMapping(value="/{expedientId}/document/{processInstanceId}/{documentStoreId}/modificar", method = RequestMethod.POST)
public String documentModificarPost(
        HttpServletRequest request,
        @PathVariable Long expedientId,
        @PathVariable String processInstanceId,
        @PathVariable Long documentStoreId,
        @ModelAttribute DocumentExpedientCommand command, 
        @RequestParam(value = "modificarArxiu", required = true) boolean modificarArxiu,
        @RequestParam(value = "arxiu", required = false) final CommonsMultipartFile arxiu,  
        @RequestParam(value = "accio", required = true) String accio,
        BindingResult result, 
        SessionStatus status, 
        Model model) {
    try {
        if (!arxiu.isEmpty()) {
            byte[] contingutArxiu = IOUtils.toByteArray(arxiu.getInputStream());
            String nomArxiu = arxiu.getOriginalFilename();
            command.setNomArxiu(nomArxiu);
            command.setContingut(contingutArxiu);
        }
        new DocumentModificarValidator().validate(command, result);
        boolean docAdjunto = !(modificarArxiu && arxiu.isEmpty());
        if (result.hasErrors() || !docAdjunto) {
            if (!docAdjunto) {
                model.addAttribute("modificarArxiu", modificarArxiu);
                MissatgesHelper.error(request, getMessage(request, "error.especificar.document"));                          
            }
            ExpedientDocumentDto document = expedientService.findDocumentPerInstanciaProces(
                    expedientId,
                    processInstanceId,
                    documentStoreId,
                    command.getCodi());
            model.addAttribute("documentExpedientCommand", command);
            model.addAttribute("processInstanceId", processInstanceId);
            model.addAttribute("document", document);       
            return "v3/expedientDocumentModificar";
        }
        expedientService.crearModificarDocument(
                expedientId,
                processInstanceId,
                documentStoreId,
                command.getNom(),
                command.getNomArxiu(),
                command.getDocId(),
                command.getContingut(),
                command.getData());
        MissatgesHelper.success(request, getMessage(request, "info.document.guardat"));
       } catch (Exception ex) {
        logger.error("No s'ha pogut guardar el document: expedientId: " + expedientId + " : documentStoreId : " + documentStoreId, ex);
        MissatgesHelper.error(request, getMessage(request, "error.proces.peticio") + ": " + ex.getLocalizedMessage());
       }
    return modalUrlTancar(false);
}
项目:communote-server    文件:AttachmentUploadController.java   
/**
 * {@inheritDoc}
 */
@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    Locale locale = sessionHandler.getCurrentLocale(request);
    ObjectNode uploadResult = null;
    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
    CommonsMultipartFile cFile = (CommonsMultipartFile) multipartRequest.getFile("file");
    String errorMessage = null;
    if (cFile != null && cFile.getSize() > 0) {
        if (cFile.getSize() < getMaxUploadSize()) {
            try {
                // create a binary content TO
                AttachmentTO binContent = new AttachmentStreamTO(cFile.getInputStream(),
                        AttachmentStatus.UPLOADED);
                binContent.setMetadata(new ContentMetadata());
                binContent.getMetadata().setFilename(cFile.getOriginalFilename());
                binContent.setContentLength(cFile.getSize());

                ResourceStoringManagement rsm = ServiceLocator
                        .findService(ResourceStoringManagement.class);
                Attachment attachment = rsm.storeAttachment(binContent);

                // save attachment IDs in session to allow removing attachments that are removed
                // from the note before publishing
                // we do not do this via separate requests because the ownership is not checked
                // when deleting the attachment
                Set<Long> uploadedFiles = CreateBlogPostFeHelper
                        .getUploadedAttachmentsFromSession(request);
                uploadedFiles.add(attachment.getId());
                uploadResult = CreateBlogPostFeHelper.createAttachmentJSONObject(attachment);
            } catch (ResourceStoringManagementException e) {
                errorMessage = getUploadExceptionErrorMessage(request, e, locale);
            }
        } else {
            errorMessage = ResourceBundleManager.instance().getText(
                    "error.blogpost.upload.filesize.limit", locale,
                    FileUtils.byteCountToDisplaySize(getMaxUploadSize()));
        }
    } else {
        errorMessage = ResourceBundleManager.instance().getText(
                "error.blogpost.upload.empty.file", locale);
    }
    ObjectNode jsonResponse;
    if (errorMessage != null) {
        jsonResponse = JsonRequestHelper.createJsonErrorResponse(errorMessage);
    } else {
        jsonResponse = JsonRequestHelper.createJsonSuccessResponse(null, uploadResult);
    }
    return ControllerHelper.prepareModelAndViewForJsonResponse(multipartRequest, response,
            jsonResponse, true);
}
项目:summerb    文件:ArticleAttachmentVm.java   
public CommonsMultipartFile getFile() {
    return file;
}
项目:summerb    文件:ArticleAttachmentVm.java   
public void setFile(CommonsMultipartFile file) {
    this.file = file;
}
项目:sakai    文件:MultiCommonsMultipartResolver.java   
@Override
protected MultipartParsingResult parseFileItems(List<FileItem> fileItems, String encoding) {
    MultiValueMap<String, MultipartFile> multipartFiles = new LinkedMultiValueMap<String, MultipartFile>();
    Map<String, String[]> multipartParameters = new HashMap<String, String[]>();
    Map<String, String> multipartParameterContentTypes = new HashMap<String, String>();

    // Extract multipart files and multipart parameters.
    for (FileItem fileItem : fileItems) {
        if (fileItem.isFormField()) {
            String value;
            String partEncoding = determineEncoding(fileItem.getContentType(), encoding);
            if (partEncoding != null) {
                try {
                    value = fileItem.getString(partEncoding);
                }
                catch (UnsupportedEncodingException ex) {
                    if (log.isWarnEnabled()) {
                        log.warn("Could not decode multipart item '" + fileItem.getFieldName() +
                                "' with encoding '" + partEncoding + "': using platform default");
                    }
                    value = fileItem.getString();
                }
            }
            else {
                value = fileItem.getString();
            }
            String[] curParam = multipartParameters.get(fileItem.getFieldName());
            if (curParam == null) {
                // simple form field
                multipartParameters.put(fileItem.getFieldName(), new String[] {value});
            }
            else {
                // array of simple form fields
                String[] newParam = StringUtils.addStringToArray(curParam, value);
                multipartParameters.put(fileItem.getFieldName(), newParam);
            }
            multipartParameterContentTypes.put(fileItem.getFieldName(), fileItem.getContentType());
        }
        else {
            // multipart file field
            CommonsMultipartFile file = new CommonsMultipartFile(fileItem);
            multipartFiles.add(fileItem.getName(), file);
            if (log.isDebugEnabled()) {
                log.debug("Found multipart file [" + file.getName() + "] of size " + file.getSize() +
                        " bytes with original filename [" + file.getOriginalFilename() + "], stored " +
                        file.getStorageDescription());
            }
        }
    }
    return new MultipartParsingResult(multipartFiles, multipartParameters, multipartParameterContentTypes);
}
项目:momo3-backend    文件:GeoServerImporterService.java   
/**
 * Generate multipart file (ZIP) for shapefile
 * @param tempDir path to temporary directory
 * @param shapeName Name pof the shapefile
 * @return MultipartFile representing ZIP file which contains parts of shapefile
 * @throws IOException
 */
private MultipartFile createShapeZip(String tempDir, String shapeName) throws IOException {
    final String basePath = tempDir +"/";
    final String zipFileName = basePath + shapeName + ".zip";
    try (
        FileOutputStream fos = new FileOutputStream(zipFileName);
        ZipOutputStream zos = new ZipOutputStream(fos);
    ) {
        // only "shp", "dbf", "shx" should be included in ZIP file so that the user must set CRS manually
        for (String ending : new String[]{"shp", "dbf", "shx"}) {
            String fileName = basePath + shapeName + "."+ending;
            File file = new File(fileName);
            try (
                FileInputStream fis = new FileInputStream(file);
            ) {
                ZipEntry zipEntry = new ZipEntry(shapeName + "."+ending);
                zos.putNextEntry(zipEntry);
                byte[] bytes = new byte[1024];
                int length;
                while ((length = fis.read(bytes)) >= 0) {
                    zos.write(bytes, 0, length);
                }

                zos.closeEntry();
            } finally {
                LOG.trace("Added " + fileName + " to ZIP file");
            }
        }
        zos.finish();
    } finally {

        // TODO get rid of warnings. make it better next playday
        final File zipFile = new File(zipFileName);
        final DiskFileItem diskFileItem = new DiskFileItem("file", "application/zip", true, zipFile.getName(), 100000000, zipFile.getParentFile());

        InputStream input =  new FileInputStream(zipFile);
        OutputStream os = diskFileItem.getOutputStream();
        IOUtils.copy(input, os);

        return new CommonsMultipartFile(diskFileItem);
    }
}
项目:particity    文件:CustomOrgServiceHandler.java   
/**
 * Add (or update) an organisation)
 *
 * @param companyId the company id
 * @param userId the user id
 * @param groupId the group id
 * @param owner the owner of the organisation
 * @param name the organisation name
 * @param holder the holder of the organisation
 * @param descr the description of the organisation
 * @param legalStatus the legal status  of the organisation
 * @param street the street address of the organisation's contact
 * @param streetNumber the street number of the organisation's contact
 * @param city the city of the organisation's contact
 * @param country the country of the organisation's contact
 * @param zip the zip of the organisation's contact
 * @param tel the telephone number of the organisation's contact
 * @param fax the fax of the organisation's contact
 * @param mail the email address of the organisation's contact
 * @param web the URL of the organisation's contact
 * @param logo the logo of the organisation (or null)
 * @return the organisation added or changed
 */
public static AHOrg addOrganisation(final long companyId,
        final long userId, final long groupId, final String owner,
        final String name,
        final String holder, final String descr, final String legalStatus,
        final String street,
        final String streetNumber, final String city, final String country,
        final String zip,
        final String tel, final String fax, final String mail,
        final String web, final CommonsMultipartFile logo, float coordsLat, float coordsLon) {
    AHOrg result = null;

    String countryName = country;

    try {
        final Long countryId = Long.parseLong(country);
        final AHCategories countryCat = AHCategoriesLocalServiceUtil
                .getCategory(countryId);
        if (countryCat != null) {
            countryName = countryCat.getName();
        }
    } catch (final Throwable t) {
        //m_objLog.warn(t);
    }

    final AHRegion region = AHRegionLocalServiceUtil.addRegion(city,
            countryName,
            zip);
    final AHAddr address = AHAddrLocalServiceUtil.addAddress(street,
            streetNumber, null, null, region.getRegionId());
    final AHContact contact = AHContactLocalServiceUtil.addContact(null,
            null,
            tel, fax, mail, web);
    // m_objLog.info("Trying to add/update an org for "+owner+" with name "+name);
    result = AHOrgLocalServiceUtil.addOrganisation(owner, name, holder,
            descr,
            legalStatus, address.getAddrId(), contact.getContactId());

    if (userId > 0 && result != null && logo != null && logo.getSize() > 0) {
        final String logoLocation = updateLogo(companyId, userId, groupId,
                result.getOrgId(), logo);
        if (logoLocation != null) {
            AHOrgLocalServiceUtil.updateLogoLocation(result.getOrgId(),
                    logoLocation);
        }
    }
    return result;
}
项目:particity    文件:CustomOrgServiceHandler.java   
public static String updateLogo(final long companyId, final long userId,
        final long groupId, final long orgId,
        final CommonsMultipartFile logo) {
    return updateLogo(companyId, userId, groupId, orgId, logo.getBytes(), logo.getOriginalFilename());
}
项目:webcurator    文件:ProfileListController.java   
@Override
protected ModelAndView handle(HttpServletRequest req, HttpServletResponse res, Object comm, BindException errors) throws Exception {
    ProfileListCommand command = (ProfileListCommand) comm;

    req.getSession().setAttribute(ProfileListController.SESSION_KEY_SHOW_INACTIVE, command.isShowInactive());
    if(command.getActionCommand().equals(ProfileListCommand.ACTION_LIST))
    {
        String defaultAgency = (String)req.getSession().getAttribute(ProfileListController.SESSION_AGENCY_FILTER);
        if(defaultAgency == null)
        {
            defaultAgency = AuthUtil.getRemoteUserObject().getAgency().getName();
        }
        command.setDefaultAgency(defaultAgency);
    }
    else if(command.getActionCommand().equals(ProfileListCommand.ACTION_FILTER))
    {
        req.getSession().setAttribute(ProfileListController.SESSION_AGENCY_FILTER, command.getDefaultAgency());
    }
    else if(command.getActionCommand().equals(ProfileListCommand.ACTION_IMPORT))
    {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) req;
        CommonsMultipartFile uploadedFile = (CommonsMultipartFile) multipartRequest.getFile("sourceFile");
        Profile profile = new Profile();
        profile.setProfile( new String(uploadedFile.getBytes()) );
        Date now = new Date();
        profile.setName("Profile Imported on "+now.toString());
        profile.setDescription("Imported");
        String importAgency = req.getParameter("importAgency");
        if(importAgency == null || importAgency.trim().equals("")) {
            profile.setOwningAgency(AuthUtil.getRemoteUserObject().getAgency());
        } else {
            long agencyOid = Long.parseLong(importAgency);
            Agency agency = agencyUserManager.getAgencyByOid(agencyOid);
            profile.setOwningAgency(agency);
        }
        // Save to the database
        try {
            profileManager.saveOrUpdate(profile);
        } 
        catch (HibernateOptimisticLockingFailureException e) {
            Object[] vals = new Object[] {profile.getName(), profile.getOwningAgency().getName()};
            errors.reject("profile.modified", vals, "profile has been modified by another user.");
        }
        return new ModelAndView("redirect:/curator/profiles/list.html");
    }


    ModelAndView mav = getView(command);
    mav.addObject(Constants.GBL_CMD_DATA, command);
    return mav;
}
项目:amediamanager    文件:User.java   
public CommonsMultipartFile getprofilePicData()
{
  return profilePicData;
}
项目:amediamanager    文件:User.java   
public void setprofilePicData(CommonsMultipartFile profilePicData)
{
  this.profilePicData = profilePicData;
}
项目:imcms    文件:ImageUploadValidator.java   
@SuppressWarnings("unchecked")
public boolean supports(Class clazz) {
    return CommonsMultipartFile.class.isAssignableFrom(clazz);
}
项目:imcms    文件:ChangeImageDataCommand.java   
public CommonsMultipartFile getFile() {
    return file;
}