Example usage for org.springframework.web.multipart.commons CommonsMultipartFile getContentType

List of usage examples for org.springframework.web.multipart.commons CommonsMultipartFile getContentType

Introduction

In this page you can find the example usage for org.springframework.web.multipart.commons CommonsMultipartFile getContentType.

Prototype

@Override
    public String getContentType() 

Source Link

Usage

From source file:org.smigo.constraints.CommonsMultipartFileMimeTypeValidator.java

public boolean isValid(CommonsMultipartFile file, ConstraintValidatorContext constraintContext) {
    log.debug("Validating:" + file.getOriginalFilename() + " contenttype:" + file.getContentType()
            + " storagedescrip:" + file.getStorageDescription());
    return file.isEmpty() || mimeTypes.contains(file.getContentType());
}

From source file:org.smigo.constraints.CommonsMultipartFileImageValidator.java

public boolean isValid(CommonsMultipartFile file, ConstraintValidatorContext constraintContext) {
    log.debug("Validating:" + file.getOriginalFilename() + " contenttype:" + file.getContentType()
            + " storagedescrip:" + file.getStorageDescription());
    if (file.isEmpty())
        return true;
    try {/*from w  ww .  jav a  2 s . co  m*/
        BufferedImage image = ImageIO.read(file.getInputStream());
        if (image.getHeight() == height && image.getWidth() == width)
            return true;
    } catch (Exception e) {
        return false;
    }
    return false;
}

From source file:com.autoupdater.server.models.Update.java

public void setFile(CommonsMultipartFile file) {
    this.file = file;
    this.fileType = file.getContentType();
}

From source file:fr.putnami.pwt.plugin.spring.file.server.controller.FileTransfertController.java

@RequestMapping(value = "/file/upload/{uploadId}", method = RequestMethod.POST)
@ResponseBody/*from  w w  w  .  j  a  v a 2  s .co  m*/
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);
    }
}

From source file:es.ucm.fdi.dalgs.activity.service.ActivityService.java

@PreAuthorize("hasPermission(#course, 'WRITE') or hasRole('ROLE_ADMIN')")
@Transactional(readOnly = false)/*from w  ww  .  ja va  2s . c om*/
public void addAttachmentToCourseActivity(Course course, FileUpload fileupload, Long id_activity,
        Long id_course, Long id_academic) throws IOException {

    Activity act = getActivity(id_activity, id_course, null, id_academic).getSingleElement();
    Attachment attach = new Attachment();
    CommonsMultipartFile file = fileupload.getFilepath();
    String key = getStorageKey(id_activity);
    String mimeType = file.getContentType();
    storageManager.putObject(bucket, key, mimeType, file.getInputStream());

    if (act.getAttachments() == null)
        act.setAttachments(new ArrayList<Attachment>());

    String aaa = storageManager.getUrl(bucket, key).toExternalForm();
    attach.setFile(aaa);
    attach.setDescription(fileupload.getDescription());
    attach.setName(fileupload.getName());
    act.getAttachments().add(attach);
    repositoryActivity.saveActivity(act);

}

From source file:es.ucm.fdi.dalgs.activity.service.ActivityService.java

@PreAuthorize("hasPermission(#course, 'WRITE') or hasPermission(#group, 'ADMINISTRATION') or hasRole('ROLE_ADMIN')")
@Transactional(readOnly = false)//from   w  ww  . j ava2 s .c  o  m
public void addAttachmentToGroupActivity(Course course, Group group, FileUpload fileupload, Long id_group,
        Long id_course, Long id_activity, Long id_academic) throws IOException {

    Attachment attach = new Attachment();
    Activity act = getActivity(id_activity, id_course, id_group, id_academic).getSingleElement();

    CommonsMultipartFile file = fileupload.getFilepath();

    String key = getStorageKey(id_activity);
    String mimeType = file.getContentType();
    storageManager.putObject(bucket, key, mimeType, file.getInputStream());
    if (act.getAttachments() == null)
        act.setAttachments(new ArrayList<Attachment>());
    String aaa = storageManager.getUrl(bucket, key).toExternalForm();
    attach.setFile(aaa);
    attach.setDescription(fileupload.getDescription());
    attach.setName(fileupload.getName());
    act.getAttachments().add(attach);
    repositoryActivity.saveActivity(act);

}

From source file:com.amediamanager.dao.DynamoDbUserDaoImpl.java

/**
 * Upload the profile pic to S3 and return it's URL
 * @param profilePic//w  w  w .  j a  va  2s  .c o  m
 * @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;
}

From source file:com.crimelab.controller.UploadController.java

@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
public ModelAndView showCompositeDetails(Model model,
        @RequestParam(value = "file") CommonsMultipartFile uploadedFile,
        @RequestParam(value = "description", required = false) String fileDescription,
        @RequestParam(value = "sococase", required = false) String soco_case) throws IOException {
    Calendar currentTimeDate = Calendar.getInstance();
    File filePath = new File(fileUploadService.getFileUploadPath() + "\\Files\\");
    ModelAndView mv = new ModelAndView("redirect:FileUpload");

    if (!filePath.exists()) {
        filePath.mkdir();//from   w w  w.  ja  v a2  s. com
    }
    String status = "success";
    try {
        uploadedFile.transferTo(new File(filePath + "\\" + uploadedFile.getOriginalFilename()));
    } catch (IllegalStateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        status = "failure";
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        status = "iofailure";
    }

    int file_type;

    String fileType = uploadedFile.getContentType();
    String getFile = uploadedFile.getOriginalFilename();
    String[] fileExtension = getFile.split("\\.", 2);

    if (fileExtension[1].contains("doc") || fileExtension[1].contains("pdf")
            || fileExtension[1].contains("xls")) {
        file_type = 0;
    } else {
        file_type = 1;
    }

    Files input = new Files();

    input.setFile_type(file_type);
    input.setOrig_file_name(uploadedFile.getOriginalFilename());
    input.setFile_name(uploadedFile.getOriginalFilename());
    input.setFile_extension(fileExtension[1]);
    input.setFile_path(filePath.toString() + "\\" + uploadedFile.getOriginalFilename());
    input.setDate(currentTimeDate.getTime());
    input.setDescription(fileDescription);
    input.setSoco_case(soco_case);
    input.setFolder_id(1); // Related field
    fileUploadService.uploadFile(input);
    //site settings for fileLocation, to edit
    mv.addObject("status", status);
    return mv;
}

From source file:alpha.portal.webapp.controller.FileUploadController.java

/**
 * On submit./*from ww w. j  av a 2  s .  c  o m*/
 * 
 * @param fileUpload
 *            the file upload
 * @param errors
 *            the errors
 * @param request
 *            the request
 * @return the string
 * @throws Exception
 *             the exception
 */
@RequestMapping(method = RequestMethod.POST)
public String onSubmit(final FileUpload fileUpload, final BindingResult errors,
        final HttpServletRequest request) throws Exception {

    if (request.getParameter("cancel") != null)
        return this.getCancelView();

    if (this.validator != null) { // validator is null during testing
        this.validator.validate(fileUpload, errors);

        if (errors.hasErrors())
            return "fileupload";
    }

    // validate a file was entered
    if (fileUpload.getFile().length == 0) {
        final Object[] args = new Object[] { this.getText("uploadForm.file", request.getLocale()) };
        errors.rejectValue("file", "errors.required", args, "File");

        return "fileupload";
    }

    final MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
    final CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest.getFile("file");

    // the directory to upload to
    final String uploadDir = this.getServletContext().getRealPath("/resources") + "/" + request.getRemoteUser()
            + "/";

    // Create the directory if it doesn't exist
    final File dirPath = new File(uploadDir);

    if (!dirPath.exists()) {
        dirPath.mkdirs();
    }

    // retrieve the file data
    final InputStream stream = file.getInputStream();

    // write the file to the file specified
    final OutputStream bos = new FileOutputStream(uploadDir + file.getOriginalFilename());
    int bytesRead;
    final byte[] buffer = new byte[8192];

    while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) {
        bos.write(buffer, 0, bytesRead);
    }

    bos.close();

    // close the stream
    stream.close();

    // place the data into the request for retrieval on next page
    request.setAttribute("friendlyName", fileUpload.getName());
    request.setAttribute("fileName", file.getOriginalFilename());
    request.setAttribute("contentType", file.getContentType());
    request.setAttribute("size", file.getSize() + " bytes");
    request.setAttribute("location",
            dirPath.getAbsolutePath() + Constants.FILE_SEP + file.getOriginalFilename());

    final String link = request.getContextPath() + "/resources" + "/" + request.getRemoteUser() + "/";
    request.setAttribute("link", link + file.getOriginalFilename());

    return this.getSuccessView();
}

From source file:org.medici.bia.validator.peoplebase.ShowUploadPortraitPersonValidator.java

/**
 * /*w w w .j av  a2  s . c  o  m*/
 * @param browse
 * @param errors
 */
private void validateImageToLoad(CommonsMultipartFile browse, Errors errors) {
    if (browse != null && browse.getSize() > 0) {
        if (!browse.getContentType().equals("image/jpeg") && !browse.getContentType().equals("image/png")) {
            errors.rejectValue("browse", "error.browse.invalidImage");
        }
        // MD: Verify if the upload file is too big
        if (browse.getSize() > 15000000) {
            errors.rejectValue("browse", "error.browse.fileDimension");
        }
    }

}