Example usage for org.springframework.web.multipart MultipartFile getOriginalFilename

List of usage examples for org.springframework.web.multipart MultipartFile getOriginalFilename

Introduction

In this page you can find the example usage for org.springframework.web.multipart MultipartFile getOriginalFilename.

Prototype

@Nullable
String getOriginalFilename();

Source Link

Document

Return the original filename in the client's filesystem.

Usage

From source file:org.openmrs.module.visitdocumentsui.ComplexObsSaver.java

public Obs saveOtherDocument(Visit visit, Person person, Encounter encounter, String fileCaption,
        MultipartFile multipartFile, String instructions) throws IOException {
    conceptComplex = context.getConceptComplex(ContentFamily.OTHER);
    prepareComplexObs(visit, person, encounter, fileCaption);

    obs.setComplexData(complexDataHelper.build(instructions, multipartFile.getOriginalFilename(),
            multipartFile.getBytes(), multipartFile.getContentType()).asComplexData());
    obs = context.getObsService().saveObs(obs, getClass().toString());
    return obs;/*from w w w . j  av a 2 s .  c om*/
}

From source file:com.egeniuss.appmarket.controller.AppManagerController.java

@RequestMapping("/uploadApp.html")
public @ResponseBody Map<String, Object> uploadApp(@RequestParam(required = false) MultipartFile app,
        HttpServletRequest request) {/*  w  w  w.j  a va 2 s  . c o m*/
    Date now = new Date();
    long time = now.getTime();
    String appFileName = app.getOriginalFilename();
    String realFileName = time + appFileName.substring(appFileName.lastIndexOf("."));
    Map<String, Object> msg = new HashMap<String, Object>();
    try {
        FileUtils.copyInputStreamToFile(app.getInputStream(), new File(appStore.concat(realFileName)));
    } catch (IOException e) {
        LOGGER.error("?", e);
        msg.put("errcode", -1);
        msg.put("errmsg", "<br/>" + e.getMessage());
        return msg;
    }
    SimpleDateFormat formator = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    StringTokenizer linemsg = new StringTokenizer(request.getParameter("releaseNote"), "\n");
    StringBuilder releaseNoteSb = new StringBuilder();
    while (linemsg.hasMoreElements()) {
        releaseNoteSb.append(linemsg.nextElement()).append("\\n");
    }
    Object[] args = new Object[] { time, request.getParameter("appKey"), request.getParameter("appPlatform"),
            request.getParameter("appEnv"), request.getParameter("versionNum"), app.getSize(),
            releaseNoteSb.toString(), realFileName, formator.format(now) };
    int[] argTypes = new int[] { Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR,
            Types.DECIMAL, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR };
    jdbcTemplate.update(
            "insert into APP_MARKET (APP_ID, APP_KEY, APP_PLATFORM, APP_ENV, VERSION_NUM, APP_SIZE, RELEASE_NOTE, FILE_NAME, CREATE_TIME) values (?, ?, ?, ?, ?, ?, ?, ?, ?)",
            args, argTypes);
    msg.put("errcode", 0);
    msg.put("errmsg", "ok");
    return msg;
}

From source file:com.pubkit.web.controller.FileUploadController.java

@RequestMapping(value = "/upload_cert", method = RequestMethod.POST)
public @ResponseBody UploadResponse handleFileUpload(@RequestParam("applicationId") String applicationId,
        @RequestParam("fileType") String fileType, @RequestParam("file") MultipartFile multipartFile) {

    LOG.debug("Upload request received for file size:" + multipartFile.getSize());
    validateAccessToken();//from  w w  w  . ja v  a 2s.  c  o m

    if (multipartFile != null && !multipartFile.isEmpty()) {
        String fileName = multipartFile.getOriginalFilename();
        try {
            if (TYPE_CERT.equalsIgnoreCase(fileType)) {
                if (!".p12".endsWith(multipartFile.getOriginalFilename())
                        || !".cert".endsWith(multipartFile.getOriginalFilename())) {
                    LOG.debug("Invalid file upload type received");

                    return new UploadResponse("Invalid file type");
                }
            }
            byte[] fileData = multipartFile.getBytes();
            String uploadId = applicationService.saveFile(fileData, fileName, multipartFile.getContentType());
            if (uploadId != null) {
                return new UploadResponse(uploadId, false, null);
            }

            return new UploadResponse("Failed to upload " + fileName);
        } catch (Exception e) {
            LOG.error("Error uploading file", e);
            return new UploadResponse("Failed to upload " + fileName);
        }
    } else {
        LOG.error("Error uploading file");
        return new UploadResponse("Failed to upload");
    }
}

From source file:org.gallery.web.controller.FileController.java

@RequestMapping(value = "/uploadfile", method = RequestMethod.POST)
public @ResponseBody Map upload(MultipartHttpServletRequest request, HttpServletResponse response) {

    log.info("uploadfile called...");
    Iterator<String> itr = request.getFileNames();
    MultipartFile mpf;
    List<DataFileEntity> list = new LinkedList<>();

    while (itr.hasNext()) {
        mpf = request.getFile(itr.next());
        String originalFilename = mpf.getOriginalFilename();
        log.info("Uploading {}", originalFilename);

        String key = UUID.randomUUID().toString();
        String storageDirectory = fileUploadDirectory;

        File file = new File(storageDirectory + File.separatorChar + key);
        try {// w  w  w.j  a v  a 2s. c  om

            // Save Images
            mpf.transferTo(file);

            // Save FileEntity
            DataFileEntity dataFileEntity = new DataFileEntity();
            dataFileEntity.setName(mpf.getOriginalFilename());
            dataFileEntity.setKey(key);
            dataFileEntity.setSize(mpf.getSize());
            dataFileEntity.setContentType(mpf.getContentType());
            dataFileDao.save(dataFileEntity);
            list.add(dataFileEntity);
        } catch (IOException e) {
            log.error("Could not upload file " + originalFilename, e);
        }
    }
    Map<String, Object> files = new HashMap<>();
    files.put("files", list);
    return files;
}

From source file:org.trpr.platform.batch.impl.spring.web.JobConfigController.java

/**
 * Controller for new job. Just adds an attribute jobName to the model. And redirects to the job edit page.
 *///from  w  ww  .j ava  2 s.  c o  m
@RequestMapping(value = "/configuration/modify_job", method = RequestMethod.POST)
public String addNewJob(ModelMap model, @RequestParam MultipartFile jobFile) {
    String jobFileName = jobFile.getOriginalFilename();
    //Check if file is empty or doesn't have an extension
    if (jobFile.isEmpty() || (jobFileName.lastIndexOf('.') < 0)) {
        model.remove("jobFile");
        model.addAttribute("Error", "File is Empty or invalid. Only .xml files can be uploaded");
        return "redirect:/configuration";
    } else if (!jobFileName.substring(jobFileName.lastIndexOf('.')).equals(".xml")) { //Check if file is .xml
        model.remove("jobFile");
        model.addAttribute("Error", "Only .xml files can be uploaded");
        return "redirect:/configuration";
    } else { //Read file to view
        boolean invalidJobFile = false;
        List<String> jobNameList = null;
        try {
            byte[] buffer = jobFile.getBytes();
            String XMLFileContents = new String(buffer);
            model.addAttribute("XMLFileContents", XMLFileContents);
            jobNameList = ConfigFileUtils.getJobName(new ByteArrayResource(jobFile.getBytes()));
            if (jobNameList == null || jobNameList.size() == 0) {
                throw new PlatformException("Empty list");
            }
        } catch (UnsupportedEncodingException e) {
            invalidJobFile = true;
        } catch (IOException e) {
            invalidJobFile = true;
        } catch (PlatformException p) {
            invalidJobFile = true;
        }
        for (String jobName : jobNameList) {
            if (jobName == null || invalidJobFile) {
                model.clear();
                model.addAttribute("Error", "invalid jobFile. Couldn't find job's name");
                return "redirect:/configuration";
            }
            if (jobService.contains(jobName)) {
                model.clear();
                model.addAttribute("Error",
                        "The JobName '" + jobName + "' already exists. Please choose another name");
                return "redirect:/configuration";
            }
        }
        model.addAttribute("jobName", jobNameList);
        return "configuration/modify/jobs/job";
    }
}

From source file:aiai.ai.launchpad.server.ServerController.java

private UploadResult uploadResource(MultipartFile file, Long taskId) {
    String originFilename = file.getOriginalFilename();
    if (originFilename == null) {
        return new UploadResult(false, "#442.01 name of uploaded file is null");
    }//from   w ww. j av  a  2s.co  m
    if (taskId == null) {
        return new UploadResult(false, "#442.87 taskId is null");
    }
    Task task = taskRepository.findById(taskId).orElse(null);
    if (task == null) {
        return new UploadResult(false, "#442.83 taskId is null");
    }

    final TaskParamYaml taskParamYaml = taskParamYamlUtils.toTaskYaml(task.getParams());

    try {
        File tempDir = DirUtils.createTempDir("upload-resource-");
        if (tempDir == null || tempDir.isFile()) {
            final String location = System.getProperty("java.io.tmpdir");
            return new UploadResult(false, "#442.04 can't create temporary directory in " + location);
        }
        final File resFile = new File(tempDir, "resource.");
        log.debug("Start storing an uploaded resource data to disk");
        try (OutputStream os = new FileOutputStream(resFile)) {
            IOUtils.copy(file.getInputStream(), os, 64000);
        }
        try (InputStream is = new FileInputStream(resFile)) {
            binaryDataService.save(is, resFile.length(), Enums.BinaryDataType.DATA,
                    taskParamYaml.outputResourceCode, taskParamYaml.outputResourceCode, false, null);
        }
    } catch (Throwable th) {
        log.error("Error", th);
        return new UploadResult(false, "#442.05 can't load snippets, Error: " + th.toString());
    }
    task.resultReceived = true;
    taskRepository.save(task);
    return OK_UPLOAD_RESULT;
}

From source file:de.zib.gndms.gndmc.dspace.SliceClient.java

@Override
public final ResponseEntity<Integer> setFileContent(final String subspace, final String sliceKind,
        final String slice, final String fileName, final MultipartFile file, final String dn) {

    return postFile(Integer.class, file.getName(), file.getOriginalFilename(),
            makeFileNameFacet(genSliceUrl(subspace, sliceKind, slice), fileName), dn);
}

From source file:org.openlmis.fulfillment.service.TemplateServiceTest.java

@Test
public void shouldValidateFileAndSetDataIfDefaultValueExpressionIsNull() throws Exception {
    MultipartFile file = mock(MultipartFile.class);
    when(file.getOriginalFilename()).thenReturn(NAME_OF_FILE);

    mockStatic(JasperCompileManager.class);
    JasperReport report = mock(JasperReport.class);
    InputStream inputStream = mock(InputStream.class);
    when(file.getInputStream()).thenReturn(inputStream);

    JRParameter param1 = mock(JRParameter.class);
    JRParameter param2 = mock(JRParameter.class);
    JRPropertiesMap propertiesMap = mock(JRPropertiesMap.class);
    JRExpression jrExpression = mock(JRExpression.class);
    String[] propertyNames = { DISPLAY_NAME };

    when(report.getParameters()).thenReturn(new JRParameter[] { param1, param2 });
    when(JasperCompileManager.compileReport(inputStream)).thenReturn(report);
    when(propertiesMap.getPropertyNames()).thenReturn(propertyNames);
    when(propertiesMap.getProperty(DISPLAY_NAME)).thenReturn(PARAM_DISPLAY_NAME);

    when(param1.getPropertiesMap()).thenReturn(propertiesMap);
    when(param1.getValueClassName()).thenReturn("String");
    when(param1.getDefaultValueExpression()).thenReturn(jrExpression);
    when(jrExpression.getText()).thenReturn("text");

    when(param2.getPropertiesMap()).thenReturn(propertiesMap);
    when(param2.getValueClassName()).thenReturn("Integer");
    when(param2.getDefaultValueExpression()).thenReturn(null);

    ByteArrayOutputStream byteOutputStream = mock(ByteArrayOutputStream.class);
    whenNew(ByteArrayOutputStream.class).withAnyArguments().thenReturn(byteOutputStream);
    ObjectOutputStream objectOutputStream = spy(new ObjectOutputStream(byteOutputStream));
    whenNew(ObjectOutputStream.class).withArguments(byteOutputStream).thenReturn(objectOutputStream);
    doNothing().when(objectOutputStream).writeObject(report);
    byte[] byteData = new byte[1];
    when(byteOutputStream.toByteArray()).thenReturn(byteData);
    Template template = new Template();

    templateService.validateFileAndInsertTemplate(template, file);

    verify(templateRepository).save(template);
    assertThat(template.getTemplateParameters().get(0).getDisplayName(), is(PARAM_DISPLAY_NAME));
}

From source file:de.blizzy.documentr.web.attachment.AttachmentController.java

@RequestMapping(value = "/saveViaJson/{projectName:" + DocumentrConstants.PROJECT_NAME_PATTERN + "}/"
        + "{branchName:" + DocumentrConstants.BRANCH_NAME_PATTERN + "}/" + "{pagePath:"
        + DocumentrConstants.PAGE_PATH_URL_PATTERN + "}/json", method = RequestMethod.POST)
@PreAuthorize("hasPagePermission(#projectName, #branchName, #pagePath, EDIT_PAGE)")
@ResponseBody/*  w  ww. ja v a  2s .c o m*/
public Map<String, Object> saveAttachmentViaJson(@PathVariable String projectName,
        @PathVariable String branchName, @PathVariable String pagePath, @RequestParam MultipartFile file,
        Authentication authentication) throws IOException {

    log.info("saving attachment via JSON: {}", file.getOriginalFilename()); //$NON-NLS-1$
    saveAttachmentInternal(projectName, branchName, pagePath, file, authentication);

    Map<String, Object> fileResult = Maps.newHashMap();
    fileResult.put("name", file.getOriginalFilename()); //$NON-NLS-1$
    fileResult.put("size", file.getSize()); //$NON-NLS-1$
    fileResult.put("url", StringUtils.EMPTY); //$NON-NLS-1$
    fileResult.put("thumbnail_url", StringUtils.EMPTY); //$NON-NLS-1$
    fileResult.put("delete_url", StringUtils.EMPTY); //$NON-NLS-1$
    fileResult.put("delete_type", StringUtils.EMPTY); //$NON-NLS-1$
    List<Map<String, Object>> filesList = Lists.newArrayList();
    filesList.add(fileResult);
    Map<String, Object> result = Maps.newHashMap();
    result.put("files", filesList); //$NON-NLS-1$
    return result;
}

From source file:org.dineth.shooter.app.view.ImageController.java

@RequestMapping(value = "/upload", method = RequestMethod.POST)
@ResponseBody//from w  ww  .ja v a  2s. c  om
public String handleFormUpload(@RequestParam("file") MultipartFile file) {

    File destination = null;
    if (!file.isEmpty()) {

        try {
            BufferedImage src = ImageIO.read(new ByteArrayInputStream(file.getBytes()));

            destination = new File(homefilefolder + file.getOriginalFilename());
            destination.mkdirs();

            ImageIO.write(src, FilenameUtils.getExtension(file.getOriginalFilename()), destination);

            //Save the id you have used to create the file name in the DB. You can retrieve the image in future with the ID.
        } catch (IOException ex) {
            Logger.getLogger(ImageController.class.getName()).log(Level.SEVERE, null, ex);
        }
    } else {
        return "bad thing";
    }
    return destination.getName();
}