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:com.tela.pms.PatientController.java

/**
 * createPatient will edit a new patient and update in the cloud db
 *//* w w w  .  j  ava 2  s.co m*/
@RequestMapping(value = "/editPatient", method = RequestMethod.POST)
public String editPatient(HttpServletRequest request, HttpServletResponse response, Model model,
        @RequestParam("file") MultipartFile file) {

    //Retrieving requests
    String patientId = request.getParameter("id");
    System.out.println(patientId);
    int id = Integer.parseInt(patientId);

    String patientName = request.getParameter("patientName");
    String age = request.getParameter("age");
    String nic = request.getParameter("nic");
    String address = request.getParameter("address");
    String gender = request.getParameter("gender");
    String contactNo = request.getParameter("contactNo");
    String email = request.getParameter("email");
    String tags = request.getParameter("tags");
    String createdAt = request.getParameter("patient_CreatedAt");
    String imagePath = request.getParameter("patient_Photo");
    String existingimagePath = request.getParameter("existingimagePath");
    System.out.println("**** img path " + imagePath);

    if (nic.equals("") || nic == null) {
        nic = "Not Available";
    }
    if (address.equals("") || address == null) {
        address = "Not Available";
    }
    if (contactNo.equals("") || contactNo == null) {
        contactNo = "Not Available";
    }
    if (email.equals("") || email == null) {
        email = "Not@Available";
    }
    if (tags.equals("") || tags == null) {
        tags = "Not Available";
    }

    //Creating a new patient
    Patient patient = new Patient();

    //Retrieving uploaded files
    MultipartFile patientPhoto = file;

    if (patientPhoto.getSize() != 0 && patientPhoto.getOriginalFilename() != null) {
        File cloud_file = null;
        try {
            cloud_file = convertFile(patientPhoto);
        } catch (IOException e1) {
            logger.info("something went wrong in coverting the file @" + new Date());
            e1.printStackTrace();
        }
        String extension = FilenameUtils.getExtension(patientPhoto.getOriginalFilename());
        Long fileSize = patientPhoto.getSize();

        if (extension.equals("JPG") || extension.equals("jpg") || extension.equals("jpeg")
                || extension.equals("JPEG")) {
            try {

                File catalinaBase = new File(System.getProperty("catalina.base")).getAbsoluteFile();
                logger.info("catalinaBase:" + catalinaBase.getAbsolutePath());

                InputStream inputStream = patientPhoto.getInputStream();
                String imageId = "patient-" + Integer.toString(id);
                String fileName = imageId + ".jpg";

                File newFile = new File(catalinaBase,
                        "webapps/pms/WEB-INF/views/images/Uploaded_images/Patients/" + fileName);

                if (!newFile.exists()) {
                    newFile.createNewFile();
                }
                OutputStream outputStream = new FileOutputStream(newFile);
                int read = 0;
                byte[] bytes = new byte[1024];

                while ((read = inputStream.read(bytes)) != -1) {
                    outputStream.write(bytes, 0, read);
                }
                imagePath = "resources/images/Uploaded_images/Patients/" + fileName;

                logger.info("Patient image successfully uploaded to local repo @" + new Date());
            } catch (FileNotFoundException e) {
                logger.info("something went wrong when patient photo uploading @" + new Date());
                e.printStackTrace();
            } catch (IOException e) {
                logger.info("something went wrong when patient photo uploading @" + new Date());
                e.printStackTrace();
            }

        } else {
            logger.info("Uploaded file is not a jpg or png " + new Date());
            if (gender.equals("Female")) {
                imagePath = "resources/images/patient-female.png";
            } else {
                imagePath = "resources/images/patient-male.png";
            }
        }

    } else {

        if (existingimagePath.contains("patient-male") || existingimagePath.contains("patient-female")) {
            if (gender.equals("Female")) {
                imagePath = "resources/images/patient-female.png";
            } else {
                imagePath = "resources/images/patient-male.png";
            }

        }
    }

    //Updating patient info
    patient.setPatient_Id(id);
    patient.setPatient_Name(patientName);
    patient.setPatient_Age(age);
    patient.setPatient_Address(address);
    patient.setPatient_ContactNo(contactNo);
    patient.setPatient_Gender(gender);
    patient.setPatient_Email(email);
    patient.setPatient_NIC(nic);
    patient.setPatient_Photo(imagePath);
    patient.setPatient_CreatedAt(createdAt);
    patient.setPatient_tags(tags);

    //Calling patient service and updating patient
    patientService.updatePatient(patient);

    //System.out.println(patientName+"  "+age+"   "+patientPhoto.getOriginalFilename()+"   "+nic+"   "+address+"   "+gender+"   "+contactNo+"   "+email);

    String view = "patient";

    Patient editedPatient = patientService.findPatientById(id);
    model.addAttribute("patient", editedPatient);

    List<Prescription> prescriptions = prescriptionService.retrieveAllPrescriptionsByPatientId(id);
    model.addAttribute("prescriptions", prescriptions);

    logger.info("Edited Patient " + id + " retrieved @ " + new Date());
    logger.info("Prescription list " + prescriptions + " retrieved @ " + new Date());
    model.addAttribute("status", "<strong>Successfully </strong> updated the patient! ");
    model.addAttribute("style", "style=\"display:block;margin-top: 5px;\"");
    return view;
}

From source file:com.example.ekanban.service.ProductService.java

@Transactional
public void addProductsBatch(MultipartFile file) {
    logger.debug("addProductsBatch");
    List<ProductCsv> list = null;
    //convert to csv string
    String output = null;//from w  w w. jav  a 2s. com
    try {
        if (file.getOriginalFilename().contains("xlsx")) {
            output = CsvUtils.fromXlsx(file.getInputStream());
        } else if (file.getOriginalFilename().contains("xls")) {
            output = CsvUtils.fromXls(file.getInputStream());
        }
        //logger.debug(output);
    } catch (IOException e) {
        e.printStackTrace();
    }

    //Read as Bean from csv String
    CSVReader reader = new CSVReader(new StringReader(output), ';');
    HeaderColumnNameMappingStrategy<ProductCsv> strategy = new HeaderColumnNameMappingStrategy<>();
    strategy.setType(ProductCsv.class);
    CsvToBean<ProductCsv> csvToBean = new CsvToBean<>();
    list = csvToBean.parse(strategy, reader);
    //Validate Product Data
    validate(list);

    //convert from DTO to ENTITY
    List<Product> products = map(list);
    productRepository.save(products);
}

From source file:org.jasig.portlet.blackboardvcportlet.service.impl.SessionServiceImpl.java

private BlackboardPresentationResponse createSessionPresentation(Session session, ConferenceUser conferenceUser,
        MultipartFile file) {
    final String filename = FilenameUtils.getName(file.getOriginalFilename());

    File multimediaFile = null;//  w  w w .  j  av a 2  s  .  co m
    try {
        //Transfer the uploaded file to our own temp file so we can use a FileDataSource
        multimediaFile = File.createTempFile(filename, ".tmp", this.tempDir);
        file.transferTo(multimediaFile);

        //Upload the file to BB
        return this.presentationWSDao.uploadPresentation(session.getBbSessionId(), conferenceUser.getUniqueId(),
                filename, "", new DataHandler(new FileDataSource(multimediaFile)));
    } catch (IOException e) {
        throw new RuntimeException("Failed to upload multimedia file '" + filename + "'", e);
    } finally {
        FileUtils.deleteQuietly(multimediaFile);
    }
}

From source file:org.jasig.portlet.blackboardvcportlet.service.impl.SessionServiceImpl.java

private BlackboardMultimediaResponse createSessionMultimedia(Session session, ConferenceUser conferenceUser,
        MultipartFile file) {
    final String filename = FilenameUtils.getName(file.getOriginalFilename());

    File multimediaFile = null;/*www  . j  a  v a  2 s  .c o m*/
    try {
        //Transfer the uploaded file to our own temp file so we can use a FileDataSource
        multimediaFile = File.createTempFile(filename, ".tmp", this.tempDir);
        file.transferTo(multimediaFile);

        //Upload the file to BB
        return this.multimediaWSDao.createSessionMultimedia(session.getBbSessionId(),
                conferenceUser.getUniqueId(), filename, "",
                new DataHandler(new FileDataSource(multimediaFile)));
    } catch (IOException e) {
        throw new RuntimeException("Failed to upload multimedia file '" + filename + "'", e);
    } finally {
        FileUtils.deleteQuietly(multimediaFile);
    }
}

From source file:com.hr_scaffold.fileservice.FileService.java

/**
 * *****************************************************************************
 * NAME: uploadFile/*from w w w . j a v a  2  s . c om*/
 * DESCRIPTION:
 * The FileUpload widget automatically calls this method whenever the user selects a new file.
 * <p/>
 * PARAMS:
 * file : multipart file to be uploaded.
 * relativePath : This is the relative path where file will be uploaded.
 * <p/>
 * RETURNS FileUploadResponse.
 * This has the following fields
 * Path: tells the client where the file was stored so that the client can identify the file to the server
 * Name: tells the client what the original name of the file was so that any
 * communications with the end user can use a filename familiar to that user.
 * Type: returns type information to the client, based on filename extensions (.txt, .pdf, .gif, etc...)
 * ******************************************************************************
 */
public FileUploadResponse[] uploadFile(MultipartFile[] files, String relativePath,
        HttpServletRequest httpServletRequest) {
    List<FileUploadResponse> wmFileList = new ArrayList<>();
    File outputFile = null;
    for (MultipartFile file : files) {
        try {
            outputFile = fileServiceManager.uploadFile(file, relativePath, uploadDirectory);
            // Create WMFile object
            wmFileList.add(new FileUploadResponse(
                    WMRuntimeUtils.getContextRelativePath(outputFile, httpServletRequest), outputFile.getName(),
                    outputFile.length(), true, ""));
        } catch (Exception e) {
            wmFileList.add(new FileUploadResponse(null, file.getOriginalFilename(), 0, false, e.getMessage()));
        }
    }
    return wmFileList.toArray(new FileUploadResponse[wmFileList.size()]);
}

From source file:com.vmware.appfactory.recipe.controller.RecipeApiController.java

@ResponseBody
@RequestMapping(value = "/recipes/uploadfile", method = RequestMethod.POST)
public RecipeFileUploadResponse uploadRecipeFile(@RequestParam(value = "recipeFile") MultipartFile recipeFile)
        throws AfBadRequestException, AfServerErrorException {
    _log.debug("Uploading recipe file");
    _log.debug("  Original Name = " + recipeFile.getOriginalFilename());
    _log.debug("  File Size     = " + recipeFile.getSize());

    try {/*from  w w  w.  j a  v a 2s.c o  m*/
        DsDatastore ds = null;
        Long dsId = Long.valueOf(_config.getLong(ConfigRegistryConstants.DATASTORE_DEFAULT_RECIPE_ID));
        _log.debug("  DS ID = " + dsId);

        if (dsId == null) {
            throw new AfBadRequestException("No datastore selected for recipe uploads");
        }

        ds = _dsClient.findDatastore(dsId, true);
        if (ds == null) {
            throw new AfBadRequestException("Invalid datastore ID " + dsId + " for recipe uploads");
        }

        /* Create a unique folder using timestamp */
        String dest = ds.createDirsIfNotExists("recipe-files", "" + AfCalendar.Now());
        _log.debug("  Created folder " + dest);

        dest = ds.buildPath(dest, recipeFile.getOriginalFilename());
        _log.debug("  Copying to " + dest);

        ds.copy(recipeFile, dest, null);
        URI uri = DsUtil.generateDatastoreURI(dsId, dest);
        _log.debug("  Copy complete: URI = " + uri.toString());

        RecipeFileUploadResponse response = new RecipeFileUploadResponse();
        response.uri = uri;
        return response;
    } catch (DsException ex) {
        throw new AfServerErrorException(ex);
    } catch (IOException ex) {
        throw new AfServerErrorException(ex);
    } catch (URISyntaxException ex) {
        throw new AfServerErrorException(ex);
    }
}

From source file:cz.zcu.kiv.eegdatabase.logic.controller.experiment.AddExperimentWizardController.java

@Override
protected ModelAndView processFinish(HttpServletRequest httpServletRequest,
        HttpServletResponse httpServletResponse, Object command, BindException e) throws Exception {
    log.debug("Processing measuration form - adding new measuration");
    ModelAndView mav = new ModelAndView("redirect:/experiments/my-experiments.html");

    mav.addObject("userIsExperimenter", auth.userIsExperimenter());

    AddExperimentWizardCommand data = (AddExperimentWizardCommand) command;

    Experiment experiment;/*from   w w w .j  a v a  2s  . c o m*/

    log.debug("Checking the permission level.");
    if (!auth.userIsExperimenter()) {
        log.debug("User is not experimenter - unable to add experiment. Returning MAV.");
        mav.setViewName("redirect:experiments/userNotExperimenter");
        return mav;
    }

    log.debug("Creating new Measuration object");
    experiment = new Experiment();

    // This assignment is commited only when new experiment is being created
    log.debug("Setting the owner to the logged user.");
    experiment.setPersonByOwnerId(personDao.getLoggedPerson());

    log.debug("Setting the group, which is the new experiment being added into.");
    ResearchGroup researchGroup = new ResearchGroup();
    researchGroup.setResearchGroupId(data.getResearchGroup());
    experiment.setResearchGroup(researchGroup);

    log.debug("Setting Weather object - ID " + data.getWeather());
    Weather weather = new Weather();
    weather.setWeatherId(data.getWeather());
    experiment.setWeather(weather);

    log.debug("Setting Scenario object - ID " + data.getScenario());
    Scenario scenario = new Scenario();
    scenario.setScenarioId(data.getScenario());
    experiment.setScenario(scenario);

    log.debug("Setting Person object (measured person) - ID " + data.getSubjectPerson());
    Person subjectPerson = new Person();
    subjectPerson.setPersonId(data.getSubjectPerson());
    experiment.setPersonBySubjectPersonId(subjectPerson);

    Date startDate = ControllerUtils.getDateFormatWithTime()
            .parse(data.getStartDate() + " " + data.getStartTime());
    experiment.setStartTime(new Timestamp(startDate.getTime()));
    log.debug("Setting start date - " + startDate);

    Date endDate = ControllerUtils.getDateFormatWithTime().parse(data.getEndDate() + " " + data.getEndTime());
    experiment.setEndTime(new Timestamp(endDate.getTime()));
    log.debug("Setting end date - " + endDate);

    log.debug("Setting the temperature - " + data.getTemperature());
    experiment.setTemperature(Integer.parseInt(data.getTemperature()));

    log.debug("Setting the weather note - " + data.getWeatherNote());
    experiment.setEnvironmentNote(data.getWeatherNote());

    log.debug("Started setting the Hardware objects");
    int[] hardwareArray = data.getHardware();
    Set<Hardware> hardwareSet = new HashSet<Hardware>();
    for (int hardwareId : hardwareArray) {
        System.out.println("hardwareId " + hardwareId);
        Hardware tempHardware = hardwareDao.read(hardwareId);
        hardwareSet.add(tempHardware);
        tempHardware.getExperiments().add(experiment);
        log.debug("Added Hardware object - ID " + hardwareId);
    }
    log.debug("Setting Hardware list to Measuration object");
    experiment.setHardwares(hardwareSet);

    log.debug("Started setting the Person objects (coExperimenters)");
    int[] coExperimentersArray = data.getCoExperimenters();
    Set<Person> coExperimenterSet = new HashSet<Person>();
    for (int personId : coExperimentersArray) {
        Person tempExperimenter = personDao.read(personId);
        coExperimenterSet.add(tempExperimenter);
        tempExperimenter.getExperiments().add(experiment);
        log.debug("Added Person object - ID " + tempExperimenter.getPersonId());
    }
    log.debug("Setting Person list to Measuration object");
    experiment.setPersons(coExperimenterSet);

    log.debug("Setting private/public access");
    experiment.setPrivateExperiment(data.isPrivateNote());
    float samplingRate = Float.parseFloat(data.getSamplingRate());
    Digitization digitization = digitizationDao.getDigitizationByParams(samplingRate, -1, "NotKnown");
    if (digitization == null) {
        digitization = new Digitization();
        digitization.setFilter("NotKnown");
        digitization.setGain(-1);
        digitization.setSamplingRate(samplingRate);
        digitizationDao.create(digitization);
    }

    experiment.setDigitization(digitization);
    experiment.setArtifact(artifactDao.read(1));
    experiment.setElectrodeConf(electrodeConfDao.read(1));
    experiment.setSubjectGroup(subjectGroupDao.read(1)); //default subject group

    if (data.getMeasurationId() > 0) { // editing existing measuration
        log.debug("Saving the Measuration object to database using DAO - update()");
        experimentDao.update(experiment);
    } else { // creating new measuration
        log.debug("Saving the Measuration object to database using DAO - create()");
        experimentDao.create(experiment);
    }

    //  log.debug("Creating measuration with ID " + addDataCommand.getMeasurationId());
    //     experiment.setExperimentId(addDataCommand.getMeasurationId());

    log.debug("Creating new Data object.");
    MultipartHttpServletRequest mpRequest = (MultipartHttpServletRequest) httpServletRequest;
    // the map containing file names mapped to files
    Map m = mpRequest.getFileMap();
    Set set = m.keySet();
    for (Object key : set) {
        MultipartFile file = (MultipartFile) m.get(key);
        if (file.getOriginalFilename().endsWith(".zip")) {
            ZipInputStream zis = new ZipInputStream(new ByteArrayInputStream(file.getBytes()));
            ZipEntry en = zis.getNextEntry();
            while (en != null) {
                if (en.isDirectory()) {
                    en = zis.getNextEntry();
                    continue;
                }
                DataFile dataFile = new DataFile();
                dataFile.setExperiment(experiment);
                String name[] = en.getName().split("/");
                dataFile.setFilename(name[name.length - 1]);
                data.setFileDescription(data.getFileDescription());
                dataFile.setFileContent(Hibernate.createBlob(zis));
                String[] partOfName = en.getName().split("[.]");
                dataFile.setMimetype(partOfName[partOfName.length - 1]);
                dataFileDao.create(dataFile);
                en = zis.getNextEntry();
            }
        } else {
            DataFile dataFile = new DataFile();
            dataFile.setExperiment(experiment);

            log.debug("Original name of uploaded file: " + file.getOriginalFilename());
            String filename = file.getOriginalFilename().replace(" ", "_");
            dataFile.setFilename(filename);

            log.debug("MIME type of the uploaded file: " + file.getContentType());
            if (file.getContentType().length() > MAX_MIMETYPE_LENGTH) {
                int index = filename.lastIndexOf(".");
                dataFile.setMimetype(filename.substring(index));
            } else {
                dataFile.setMimetype(file.getContentType());
            }

            log.debug("Parsing the sapmling rate.");
            dataFile.setDescription(data.getFileDescription());

            log.debug("Setting the binary data to object.");
            dataFile.setFileContent(Hibernate.createBlob(file.getBytes()));

            dataFileDao.create(dataFile);
            log.debug("Data stored into database.");
        }
    }

    log.debug("Returning MAV object");
    return mav;
}

From source file:com.prcsteel.platform.order.web.controller.cust.AccountController.java

private boolean checkUploadAttachment(MultipartFile file, HashMap<String, Object> result,
        List<MultipartFile> attachmentList) {
    String suffix = FileUtil.getFileSuffix(file.getOriginalFilename());

    if (suffix == null || !Constant.IMAGE_SUFFIX.contains(suffix.toLowerCase())) {
        result.put("data", AttachmentType.valueOf(file.getName()).getName() + "??");
        return false;
    }//from  w  w w. j a va2s. c  o m
    if (file.getSize() / Constant.M_SIZE > Constant.MAX_IMG_SIZE) {
        result.put("data",
                AttachmentType.valueOf(file.getName()).getName() + "" + Constant.MAX_IMG_SIZE + "M");
        return false;
    }
    attachmentList.add(file);
    return true;
}

From source file:com.dlshouwen.wzgl.picture.controller.PictureController.java

/**
 * /*from  w ww .j  a  va 2s  .  co  m*/
 *
 * @param picture 
 * @param bindingResult ?
 * @param request 
 * @return ajax?
 */
@RequestMapping(value = "/{albumId}/ajaxMultipartAdd", method = RequestMethod.POST)
public void ajaxAddMultipartPictureAl(@Valid Picture picture, BindingResult bindingResult,
        HttpServletRequest request, HttpServletResponse response, @PathVariable String albumId)
        throws Exception {
    //      AJAX?
    AjaxResponse ajaxResponse = new AjaxResponse();
    String flag = request.getParameter("flag");
    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
    MultipartFile multipartFile = multipartRequest.getFile("file");
    String sname = multipartFile.getOriginalFilename();
    //?
    String path = null;
    if (null != multipartFile && StringUtils.isNotEmpty(multipartFile.getOriginalFilename())) {
        JSONObject jobj = FileUploadClient.upFile(request, multipartFile.getOriginalFilename(),
                multipartFile.getInputStream());
        if (jobj.getString("responseMessage").equals("OK")) {
            path = jobj.getString("fpath");
        }
    }

    /*
     String fileName = multipartFile.getOriginalFilename();
     int pos = fileName.lastIndexOf(".");
     fileName = fileName.substring(pos);
     String fileDirPath = request.getSession().getServletContext().getRealPath("/");
     String path = fileDirPath.substring(0, fileDirPath.lastIndexOf(File.separator)) + CONFIG.UPLOAD_PIC_PATH;
     Date date = new Date();
     fileName = String.valueOf(date.getTime()) + fileName;
     File file = new File(path);
     if (!file.exists()) {
     file.mkdirs();
     }
     file = new File(path + "/" + fileName);
     if (!file.exists()) {
     file.createNewFile();
     }
     path = path + "/" + fileName;
     FileOutputStream fos = null;
     InputStream s = null;
     try {
     fos = new FileOutputStream(file);
     s = multipartFile.getInputStream();
     byte[] buffer = new byte[1024];
     int read = 0;
     while ((read = s.read(buffer)) != -1) {
     fos.write(buffer, 0, read);
     }
     fos.flush();
     } catch (Exception e) {
     e.printStackTrace();
     } finally {
     if (fos != null) {
     fos.close();
     }
     if (s != null) {
     s.close();
     }
     }
     */
    if (StringUtils.isNotEmpty(path)) {
        //       ????
        SessionUser sessionUser = (SessionUser) request.getSession().getAttribute(CONFIG.SESSION_USER);
        String userId = sessionUser.getUser_id();
        String userName = sessionUser.getUser_name();
        Date nowDate = new Date();

        //      ??
        picture.setPicture_name(sname);
        //       ?   
        picture.setPicture_id(new GUID().toString());
        picture.setCreate_time(nowDate);
        picture.setUser_id(userId);
        picture.setUser_name(userName);
        path = path.replaceAll("\\\\", "/");
        picture.setPath(path);
        picture.setAlbum_id(albumId);
        picture.setFlag("1");
        picture.setShow("1");
        picture.setUpdate_time(new Date());

        //       
        dao.insertPicture(picture);

        //??
        if (flag.equals("article")) {
            Album alb = albumDao.getAlbumById(albumId);
            if (StringUtils.isEmpty(alb.getAlbum_coverpath())) {
                albumDao.setAlbCover(albumId, picture.getPath());
            }
        }

        //       ????
        ajaxResponse.setSuccess(true);
        ajaxResponse.setSuccessMessage("??");
    } else {
        //       ????
        ajaxResponse.setError(true);
        ajaxResponse.setErrorMessage("?");
    }

    //      ?
    LogUtils.updateOperationLog(request, OperationType.INSERT,
            "?" + picture.getPicture_id());

    response.setContentType("text/html;charset=utf-8");
    JSONObject obj = JSONObject.fromObject(ajaxResponse);
    response.getWriter().write(obj.toString());
    return;
}