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.feedback.web.AddFeedbackFormController.java

@Override
protected Boolean formBackingObject(HttpServletRequest request) throws Exception {

    /* To check wheather or not the subject , severity and feedback is empty or not */
    Boolean feedbackMessage = false;
    String text = "";
    String subject = request.getParameter("subject");
    String severity = request.getParameter("severity");
    String feedback = request.getParameter("feedback");

    if (StringUtils.hasLength(subject) && StringUtils.hasLength(severity) && StringUtils.hasLength(severity)) {
        Object o = Context.getService(FeedbackService.class);
        FeedbackService service = (FeedbackService) o;
        Feedback s = new Feedback();

        s.setSubject(request.getParameter("subject"));
        s.setSeverity(request.getParameter("severity"));

        /* To get the Stacktrace of the page from which the feedback is submitted */
        StackTraceElement[] c = Thread.currentThread().getStackTrace();

        if ("Yes".equals(request.getParameter("pagecontext"))) {
            for (int i = 0; i < c.length; i++) {
                feedback = feedback + System.getProperty("line.separator") + c[i].getFileName()
                        + c[i].getMethodName() + c[i].getClass() + c[i].getLineNumber();
            }//  w  ww  . j a v a  2  s  .co m
        }

        s.setContent(feedback);

        /* file upload in multiplerequest */
        if (request instanceof MultipartHttpServletRequest) {
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            MultipartFile file = (MultipartFile) multipartRequest.getFile("file");

            if (!file.isEmpty()) {
                if (file.getSize() <= 5242880) {
                    if (file.getOriginalFilename().endsWith(".jpeg")
                            || file.getOriginalFilename().endsWith(".jpg")
                            || file.getOriginalFilename().endsWith(".gif")
                            || file.getOriginalFilename().endsWith(".png")) {
                        s.setMessage(file.getBytes());
                    } else {
                        request.getSession().setAttribute(WebConstants.OPENMRS_ERROR_ATTR,
                                "feedback.notification.feedback.error");

                        return false;
                    }
                } else {
                    request.getSession().setAttribute(WebConstants.OPENMRS_ERROR_ATTR,
                            "feedback.notification.feedback.error");

                    return false;
                }
            }
        }

        /* Save the Feedback */
        service.saveFeedback(s);
        request.getSession().setAttribute(WebConstants.OPENMRS_MSG_ATTR,
                Context.getAdministrationService().getGlobalProperty("feedback.ui.notification"));

        if ("Yes".equals(Context.getUserContext().getAuthenticatedUser()
                .getUserProperty("feedback_notificationReceipt"))) {
            try {

                // Create Message
                Message message = new Message();

                message.setSender(
                        Context.getAdministrationService().getGlobalProperty("feedback.notification.email"));
                message.setRecipients(
                        Context.getUserContext().getAuthenticatedUser().getUserProperty("feedback_email"));
                message.setSubject("Feedback submission confirmation mail");
                message.setContent(Context.getAdministrationService().getGlobalProperty("feedback.notification")
                        + "Ticket Number: " + s.getFeedbackId() + " Subject :" + s.getSubject());
                message.setSentDate(new Date());

                // Send message
                Context.getMessageService().send(message);
            } catch (Exception e) {
                log.error("Unable to sent the email to the Email : "
                        + Context.getUserContext().getAuthenticatedUser().getUserProperty("feedback_email"));
            }
        }

        try {

            // Create Message
            Message message = new Message();

            message.setSender(
                    Context.getAdministrationService().getGlobalProperty("feedback.notification.email"));
            message.setRecipients(
                    Context.getAdministrationService().getGlobalProperty("feedback.admin.notification.email"));
            message.setSubject("New feedback submitted");
            message.setContent(
                    Context.getAdministrationService().getGlobalProperty("feedback.admin.notification")
                            + "Ticket Number: " + s.getFeedbackId() + " Subject : " + s.getSubject()
                            + " Take Action :" + request.getScheme() + "://" + request.getServerName() + ":"
                            + request.getServerPort() + request.getContextPath()
                            + "/module/feedback/feedback.form?feedbackId=" + s.getFeedbackId() + "#command");
            message.setSentDate(new Date());

            // Send message
            Context.getMessageService().send(message);
        } catch (Exception e) {
            log.error("Unable to sent the email to the Email : " + Context.getUserContext()
                    .getAuthenticatedUser().getUserProperty("feedback.admin.notification.email"));
        }

        feedbackMessage = true;
    }

    /* Reserved for future use for showing that the data is saved and the feedback is submitted */
    log.debug("Returning hello world text: " + text);

    return feedbackMessage;
}

From source file:com.company.project.web.controller.FileUploadController.java

@RequestMapping(value = "/singleSave", method = RequestMethod.POST)
public @ResponseBody String singleSave(@RequestParam("file") MultipartFile file,
        @RequestParam("desc") String desc) {
    System.out.println("File Description:" + desc);
    String fileName = null;//from   w w w. j a v  a2s .  c o m
    if (!file.isEmpty()) {
        try {
            fileName = file.getOriginalFilename();
            byte[] bytes = file.getBytes();
            BufferedOutputStream buffStream = new BufferedOutputStream(
                    new FileOutputStream(new File("C:/cp/" + fileName)));
            buffStream.write(bytes);
            buffStream.close();
            return "You have successfully uploaded " + fileName;
        } catch (Exception e) {
            return "You failed to upload " + fileName + ": " + e.getMessage();
        }
    } else {
        return "Unable to upload. File is empty.";
    }
}

From source file:org.projectbuendia.openmrs.web.controller.ProfileManager.java

/** Handles an uploaded profile. */
private void addProfile(MultipartHttpServletRequest request, ModelMap model) {
    List<String> lines = new ArrayList<>();
    MultipartFile mpf = request.getFile("file");
    if (mpf != null) {
        String message = "";
        String filename = mpf.getOriginalFilename();
        try {/*from   ww  w . jav  a 2 s  .com*/
            File tempFile = File.createTempFile("profile", null);
            mpf.transferTo(tempFile);
            boolean exResult = execute(VALIDATE_CMD, tempFile, lines);
            if (exResult) {
                filename = getNextVersionedFilename(filename);
                File newFile = new File(profileDir, filename);
                FileUtils.moveFile(tempFile, newFile);
                model.addAttribute("success", true);
                message = "Success adding profile: ";
            } else {
                model.addAttribute("success", false);
                message = "Error adding profile: ";
            }
        } catch (Exception e) {
            model.addAttribute("success", false);
            message = "Problem saving uploaded profile: ";
            lines.add(e.getMessage());
            log.error("Problem saving uploaded profile", e);
        } finally {
            model.addAttribute("operation", "add");
            model.addAttribute("message", message + filename);
            model.addAttribute("filename", filename);
            model.addAttribute("output", StringUtils.join(lines, "\n"));
        }
    }
}

From source file:com.gisnet.cancelacion.web.controller.NotarioController.java

private void guardaCancelacionArchivo(MultipartFile file) throws IOException {
    CancelacionArchivoInfo archivo = new CancelacionArchivoInfo();
    archivo.setArchivo(file.getBytes());
    archivo.setNombre(file.getOriginalFilename());
    archivo.setMimetype(file.getContentType());
    sesion.getCancelacionArchivos().add(archivo);
}

From source file:org.pdfgal.pdfgalweb.services.impl.SplitServiceImpl.java

@Override
public DownloadForm split(final MultipartFile file, final SplitMode splitMode, final String pages,
        final HttpServletResponse response) throws Exception {

    DownloadForm result = new DownloadForm();

    if (!file.isEmpty() && splitMode != null && StringUtils.isNotEmpty(pages)) {

        final String originalName = file.getOriginalFilename();
        final String inputUri = this.fileUtils.saveFile(file);
        String outputUri = this.fileUtils.getAutogeneratedName(originalName);
        List<String> outputUris = new ArrayList<String>();

        try {//from  w w  w  . j  a  v a2  s .  c  o m

            if (splitMode.equals(SplitMode.NUMBER_OF_PAGES)) {
                outputUris = this.splitNumberOfPages(file, pages, inputUri, outputUri);

            } else if (splitMode.equals(SplitMode.CONCRETE_PAGES_TO_SPLIT)) {
                outputUris = this.splitConcretePages(file, pages, inputUri, outputUri);

            }

            // If everything is OK, created files are put into a ZIP file
            outputUri = this.fileUtils.prepareZipFile(outputUris, originalName);
            // Temporal files are deleted from system (outputUris has
            // already been deleted).
            this.fileUtils.delete(inputUri);

            final String zipName = this.fileUtils.getFileNameWithoutExtension(originalName) + ".zip";
            result = new DownloadForm(outputUri, zipName);

        } catch (final Exception e) {
            // Temporal files are deleted from system (outputUris has
            // already been deleted).
            this.fileUtils.delete(inputUri);
            this.fileUtils.delete(outputUri);
            throw e;
        }
    }

    return result;
}

From source file:com.dlshouwen.tdjs.album.controller.TdjsAlbumController.java

/**
 * /*from w ww  .  j  av a  2s  .  co m*/
 *
 * @param album 
 * @param bindingResult 
 * @return ajax?
 * @throws Exception 
 */
@RequestMapping(value = "/edit", method = RequestMethod.POST)
public void editAlbum(@Valid Album album, HttpServletRequest request, BindingResult bindingResult,
        HttpServletResponse response) throws Exception {
    //      AJAX?
    AjaxResponse ajaxResponse = new AjaxResponse();
    //      ??
    if (bindingResult.hasErrors()) {
        ajaxResponse.bindingResultHandler(bindingResult);
        //           ?
        LogUtils.updateOperationLog(request, OperationType.UPDATE,
                "id" + album.getAlbum_id() + "??"
                        + album.getAlbum_name() + "?"
                        + AjaxResponse.getBindingResultMessage(bindingResult) + "");
        response.setContentType("text/html;charset=utf-8");
        JSONObject obj = JSONObject.fromObject(ajaxResponse);
        response.getWriter().write(obj.toString());
        return;
    }
    String path = "";
    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
    MultipartFile multipartFile = multipartRequest.getFile("picture");
    String orgFileName = multipartFile.getOriginalFilename();
    if (multipartFile != null && StringUtils.isNotEmpty(orgFileName)) {
        JSONObject jobj = FileUploadClient.upFile(request, orgFileName, multipartFile.getInputStream());
        if (jobj != null && jobj.getString("responseMessage").equals("OK")) {
            path = jobj.getString("fpath");
        }
    }
    //      ??
    album.setAlbum_coverpath(path);
    //   ????
    Date nowDate = new Date();
    //      ?
    album.setAlbum_updatedate(nowDate);

    //      
    dao.updateAlbum(album);
    //      ????
    ajaxResponse.setSuccess(true);
    ajaxResponse.setSuccessMessage("??");
    //?
    Map map = new HashMap();
    map.put("URL", "tdjs/tdjsAlbum/album");
    ajaxResponse.setExtParam(map);

    //      ?
    LogUtils.updateOperationLog(request, OperationType.UPDATE,
            "id" + album.getAlbum_id() + "??" + album.getAlbum_name());
    response.setContentType("text/html;charset=utf-8");
    JSONObject obj = JSONObject.fromObject(ajaxResponse);
    response.getWriter().write(obj.toString());
}

From source file:com.dlshouwen.tdjs.video.controller.TdjsVideoController.java

/**
 * //from w ww. j av a  2s  . co m
 *
 * @param request
 * @return
 * @throws Exception
 */
@RequestMapping(value = "/upload", method = RequestMethod.POST)
@ResponseBody
public AjaxResponse uploadVideo(HttpServletRequest request, HttpServletResponse response) throws Exception {

    String path = "";
    String videoTime = "";
    String coverPath = "";
    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
    MultipartFile multipartFile = multipartRequest.getFile("file");
    String fileName = multipartFile.getOriginalFilename();
    if (multipartFile != null && StringUtils.isNotEmpty(fileName)) {
        JSONObject jobj = FileUploadClient.upFile(request, fileName, multipartFile.getInputStream());
        if (jobj != null && jobj.getString("responseMessage").equals("OK")) {
            path = jobj.getString("fpath");
            //
            videoTime = jobj.getString("videoTime");
            coverPath = jobj.getString("videoCoverPath");
        }
    }
    WebUtil.addCookie(request, response, "videoPath", path, -1);
    WebUtil.addCookie(request, response, "videoTime", videoTime, -1);
    WebUtil.addCookie(request, response, "coverPath", coverPath, -1);

    //      ?
    AjaxResponse ajaxResponse = new AjaxResponse();
    ajaxResponse.setSuccess(true);
    ajaxResponse.setSuccessMessage("???");
    //      ?
    LogUtils.updateOperationLog(request, OperationType.UPDATE,
            "??" + fileName);
    return ajaxResponse;
}

From source file:br.com.alura.casadocodigo.infra.FileSaver.java

public String write(String baseFolder, MultipartFile file) {
    try {//ww  w  . ja va  2s  . com
        System.out.println("baseFolder " + baseFolder);
        System.out.println("file " + file);

        String realPath = request.getServletContext().getRealPath("/") + baseFolder;
        //String realPath = "H:\\Alura\\casadocodigo\\src\\main\\webapp\\arquivos-sumario";
        System.out.println("realPath " + realPath);
        String path = realPath + "\\" + file.getOriginalFilename();

        //  String filePath = request.getServletContext().getRealPath("/");

        System.out.println("path " + path);
        file.transferTo(new File(path));

        System.out.println("retorno " + baseFolder + "\\" + file.getOriginalFilename());
        return baseFolder + "/" + file.getOriginalFilename();
    } catch (IOException | IllegalStateException ex) {
        throw new RuntimeException(ex);
    }

}

From source file:org.davidmendoza.fileUpload.web.VideoController.java

@RequestMapping(value = "/upload", method = RequestMethod.POST)
public @ResponseBody Map upload(MultipartHttpServletRequest request, HttpServletResponse response) {
    log.debug("upload Post called");
    Iterator<String> itr = request.getFileNames();
    MultipartFile mpf;
    List<Video> list = new LinkedList<>();

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

        String newFilenameBase = UUID.randomUUID().toString();
        String originalFileExtension = mpf.getOriginalFilename()
                .substring(mpf.getOriginalFilename().lastIndexOf("."));
        String newFilename = newFilenameBase + originalFileExtension;
        String storageDirectory = getRealPath(request);
        String contentType = mpf.getContentType();

        File newFile = new File(storageDirectory + "/" + newFilename);
        try {/*ww w . j  av  a 2s.  c o  m*/
            mpf.transferTo(newFile);

            Video video = new Video();
            video.setName(mpf.getOriginalFilename());
            video.setNewFilename(newFilename);
            video.setContentType(contentType);
            video.setSize(mpf.getSize());
            video = videoDao.create(video);

            video.setDeleteUrl("/video/delete/" + video.getId());
            video.setDeleteType("DELETE");

            list.add(video);

        } catch (IOException e) {
            log.error("Could not upload file " + mpf.getOriginalFilename(), e);
        }

    }

    Map<String, Object> files = new HashMap<>();
    files.put("files", list);
    return files;
}

From source file:org.fenixedu.ulisboa.integration.sas.ui.spring.controller.manageScholarshipReportRequests.ScholarshipReportRequestController.java

@RequestMapping(value = "/createscholarshipreportrequeststep2", method = RequestMethod.POST)
public String createscholarshipreportrequeststep2(
        @RequestParam(value = "executionyear", required = false) ExecutionYear executionYear,
        @RequestParam(value = "firstyearofcycle", required = false) boolean firstYearOfCycle,
        @RequestParam(value = "contractualisation", required = false) boolean contractualisation,
        @RequestParam(value = "file") MultipartFile file, Model model, RedirectAttributes redirectAttributes) {

    try {//  w ww.  j  av a 2  s  .c o m

        ScholarshipReportRequest scholarshipReportRequest = createScholarshipReportRequest(executionYear,
                firstYearOfCycle, contractualisation, file.getOriginalFilename(), file.getBytes());

        model.addAttribute("scholarshipReportRequest", scholarshipReportRequest);
        return redirect("/integration/sas/managescholarshipreportrequests/scholarshipreportrequest/", model,
                redirectAttributes);
    } catch (DomainException de) {
        addErrorMessage(" Error creating due to " + de.getLocalizedMessage(), model);
        return createscholarshipreportrequeststep2(model, executionYear, firstYearOfCycle, contractualisation);
    } catch (IOException e) {
        //TODO what to do here?
        addErrorMessage(" Error reading submitted file", model);
        return createscholarshipreportrequeststep2(model, executionYear, firstYearOfCycle, contractualisation);
    }
}