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.xx.backend.controller.EmployeeController.java

@RequestMapping(value = "/form_upload2.html")
public @ResponseBody String upload(@RequestParam(value = "file", required = false) MultipartFile file,
        HttpServletRequest request, ModelMap model) {

    System.out.println("");
    String path = request.getSession().getServletContext().getRealPath("upload");
    String fileName = file.getOriginalFilename();
    //        String fileName = new Date().getTime()+".jpg";  
    System.out.println(path);//from  w ww  .ja  v  a  2 s.  c  o m
    File targetFile = new File(path, fileName);
    if (!targetFile.exists()) {
        targetFile.mkdirs();
    }

    //?  
    try {
        file.transferTo(targetFile);
    } catch (Exception e) {
        e.printStackTrace();
    }
    model.addAttribute("fileUrl", request.getContextPath() + "/upload/" + fileName);
    Map paramsMap = new QMap(200);
    return JSONObject.toJSONString(paramsMap);
}

From source file:it.geosolutions.operations.OperationEngineController.java

/**
 *  Issue a POST request to the desired Operation
 * @param operationId//w ww  . j  a v a  2s  .com
 * @param gotParam
 * @param gotHeaders
 * @param uploadFile
 * @param request
 * @param model
 * @return template jsp to display returned message
 */
@RequestMapping(value = "/operation/{operationId}/{gotParam:.+}", method = RequestMethod.POST)
public String issuePostToOperation(@PathVariable(value = "operationId") String operationId,
        @PathVariable(value = "gotParam") String gotParam, @RequestHeader HttpHeaders gotHeaders,
        @ModelAttribute("uploadFile") FileUpload uploadFile, HttpServletRequest request, ModelMap model) {

    System.out.println("Handling by issuePostToOperation : OperationEngine POST");

    if (applicationContext.containsBean(operationId)
            && applicationContext.isTypeMatch(operationId, Operation.class)) {

        Operation operation = (Operation) applicationContext.getBean(operationId);

        if (operation instanceof GeoBatchOperation) {

            String response = "Operation running"; // Default text
            try {
                GeoBatchRESTClient client = new GeoBatchRESTClient();
                client.setGeostoreRestUrl(((GeoBatchOperation) operation).getGeobatchRestUrl());
                client.setUsername(((GeoBatchOperation) operation).getGeobatchUsername());
                client.setPassword(((GeoBatchOperation) operation).getGeobatchPassword());

                // TODO: check ping to GeoBatch (see test)

                RESTFlowService service = client.getFlowService();

                if (operation instanceof RemoteOperation) {
                    // TODO: better implementation
                    byte[] blob = (byte[]) ((RemoteOperation) operation).getBlob(uploadFile.getFiles().get(0));
                    // TODO: fastFail or not?
                    // TODO: move fastfail to interfaces
                    response = service.run(((RemoteOperation) operation).getFlowID(), true, blob);
                } else if (operation instanceof LocalOperation) {

                    // TODO: implement request parameters instead of gotParam
                    RESTRunInfo runInfo;
                    if (gotParam != null) {
                        runInfo = (RESTRunInfo) ((LocalOperation) operation).getBlob(gotParam);
                    } else {

                        @SuppressWarnings("unchecked")
                        Map<String, String[]> parameters = request.getParameterMap();
                        runInfo = (RESTRunInfo) ((LocalOperation) operation).getBlob(parameters);
                    }

                    // TODO: fastFail or not?
                    // TODO: move fastfail to interfaces
                    response = service.runLocal(((LocalOperation) operation).getFlowID(), true, runInfo);

                } else {

                    // TODO: refactor this
                    Object[] obj = new Object[3];
                    obj[0] = service;
                    obj[1] = request;
                    obj[2] = model;

                    response = (String) ((GeoBatchOperation) operation).getBlob(obj);
                    return response;

                }

            } catch (Exception e) {
                e.printStackTrace();
                model.addAttribute("messageType", "error");
                model.addAttribute("operationMessage", "Couldn't run " + operation.getName());
                return "common/messages";

            }

            model.addAttribute("messageType", "success");
            model.addAttribute("operationMessage", response);

            return "common/messages";

        }

        List<MultipartFile> files = uploadFile.getFiles();

        @SuppressWarnings("unchecked")
        Map<String, String[]> parameters = request.getParameterMap();

        for (String key : parameters.keySet()) {
            System.out.println(key);
            String[] vals = parameters.get(key);
            for (String val : vals)
                System.out.println(" -> " + val);
        }
        /*
               System.out.println("-- HEADERS --");
               for( Object o : gotHeaders.keySet()) {
                           
                   //System.out.println( o.getClass().getName() );
                   System.out.println( o );
                   //System.out.println( gotHeaders.get(o).getClass().getName() );
                   System.out.println( " -> "+ gotHeaders.get(o) );
                           
                }
                */

        if (null != files && files.size() > 0) {
            for (MultipartFile multipartFile : files) {
                String fileName = multipartFile.getOriginalFilename();
                /*
                               if(!"".equalsIgnoreCase(fileName)){
                                   //Handle file content - multipartFile.getInputStream()
                                   try {
                                 multipartFile.transferTo(new File(baseDir + fileName));
                              } catch (IllegalStateException e) {
                                 e.printStackTrace();
                              } catch (IOException e) {
                                 e.printStackTrace();
                              }
                                   fileNames.add(fileName);
                               }*/
                System.out.println("File Name: " + fileName);

            }
        }

        // TODO: getJSP should modify Model adding it's own attributes
        // Maybe the setCommonModel can be called from within the Operation ?

        model.addAttribute("gotParam", gotParam);
        String operationJsp = operation.getJsp(model, request, files);

        model.addAttribute("context", "context/" + operationJsp);
        // Geosolutions authentication
        ControllerUtils.setCommonModel(model);

        return "template";

    } else {
        model.addAttribute("messageType", "error");
        model.addAttribute("operationMessage", "Operation not found");
        return "common/messages";
    }

}

From source file:com.card.loop.xyz.controller.LearningElementController.java

@RequestMapping(value = "/upload", method = RequestMethod.POST)
public ModelAndView upload(@RequestParam("title") String title, @RequestParam("author") String author,
        @RequestParam("subject") String subject, @RequestParam("description") String description,
        @RequestParam("file") MultipartFile file, @RequestParam("type") String type) {
    if (!file.isEmpty()) {
        try {/* w  ww .  j av a  2s  .c o  m*/
            byte[] bytes = file.getBytes();
            File fil = new File(AppConfig.USER_VARIABLE + AppConfig.LE_FILE_PATH + file.getOriginalFilename());

            if (!fil.getParentFile().exists()) {
                fil.getParentFile().mkdirs();
            }

            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(fil));
            stream.write(bytes);
            stream.close();

            LearningElement le = new LearningElement();
            le.setTitle(title);
            le.setUploadedBy(author);
            le.setDescription(description);
            le.setDownloads(0);
            le.setStatus(1);
            le.setRating(1);
            le.setUploadDate(new Date());
            le.setSubject(subject);
            le.setFilePath(AppConfig.LE_FILE_PATH);
            le.setFilename(file.getOriginalFilename());
            le.setContentType(file.getOriginalFilename().split("\\.")[1]);
            dao.addLearningElement(le);

            System.out.println("UPLOAD LE FINISHED");

        } catch (Exception e) {
            System.err.println(e.toString());
        }
    } else {
        System.err.println("EMPTY FILE.");
    }
    return new ModelAndView("developer-le-loop-redirect");
}

From source file:com.emergya.persistenceGeo.web.RestResourcesController.java

/**
 * This method upload a resource to server
 * //  ww  w. j  a v  a 2  s  .com
 * @param uploadResource
 */
@RequestMapping(value = "/persistenceGeo/uploadResource", method = RequestMethod.POST)
public ModelAndView uploadFile(@RequestParam(value = "uploadfile") MultipartFile uploadfile) {
    ModelAndView model = new ModelAndView();
    String result = null;
    if (uploadfile != null) {
        try {
            Long id = RANDOM.nextLong();
            result = "{\"results\": 1, \"data\": \"" + id + "_" + uploadfile.getOriginalFilename()
                    + "\", \"success\": true}";
            ResourceDto resource = multipartFileToResource(uploadfile, id);
            loadFiles.put(id, resource);
            resourceService.create(resource); //FIXME: only when a layer has been saved!!
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    } else {
        result = "{\"results\": 0, \"data\": \"\", \"success\": false}";
    }
    model.addObject("resultado", result);
    model.setViewName("resultToJSON");
    return model;
}

From source file:com.glaf.core.web.springmvc.FileUploadController.java

@ResponseBody
@RequestMapping("/upload")
public void upload(HttpServletRequest request, HttpServletResponse response) {
    response.setContentType("text/plain;charset=UTF-8");
    LoginContext loginContext = RequestUtils.getLoginContext(request);
    String serviceKey = request.getParameter("serviceKey");
    String responseType = request.getParameter("responseType");
    Map<String, Object> paramMap = RequestUtils.getParameterMap(request);
    logger.debug("paramMap:" + paramMap);
    MultipartHttpServletRequest req = (MultipartHttpServletRequest) request;
    String type = req.getParameter("type");
    if (StringUtils.isEmpty(type)) {
        type = "0";
    }//from  ww w.  jav  a2 s  .  c om
    int maxUploadSize = conf.getInt(serviceKey + ".maxUploadSize", 0);
    if (maxUploadSize == 0) {
        maxUploadSize = conf.getInt("upload.maxUploadSize", 50);// 50MB
    }
    maxUploadSize = maxUploadSize * FileUtils.MB_SIZE;

    /**
     * ?maxDiskSize,5MB
     */
    int maxDiskSize = conf.getInt(serviceKey + ".maxDiskSize", 0);
    if (maxDiskSize == 0) {
        maxDiskSize = conf.getInt("upload.maxDiskSize", 1024 * 1024 * 2);// 2MB
    }

    logger.debug("maxUploadSize:" + maxUploadSize);
    String uploadDir = Constants.UPLOAD_PATH;
    InputStream inputStream = null;
    try {
        PrintWriter out = response.getWriter();
        Map<String, MultipartFile> fileMap = req.getFileMap();
        Set<Entry<String, MultipartFile>> entrySet = fileMap.entrySet();
        for (Entry<String, MultipartFile> entry : entrySet) {
            MultipartFile mFile = entry.getValue();
            logger.debug("fize size:" + mFile.getSize());
            if (mFile.getOriginalFilename() != null && mFile.getSize() > 0 && mFile.getSize() < maxUploadSize) {
                String filename = mFile.getOriginalFilename();
                logger.debug("upload file:" + filename);
                logger.debug("fize size:" + mFile.getSize());
                String fileId = UUID32.getUUID();

                // ????
                String autoCreatedDateDirByParttern = "yyyy/MM/dd";
                String autoCreatedDateDir = DateFormatUtils.format(new java.util.Date(),
                        autoCreatedDateDirByParttern);
                String rootDir = SystemProperties.getConfigRootPath();
                if (!rootDir.endsWith(String.valueOf(File.separatorChar))) {
                    rootDir = rootDir + File.separatorChar;
                }
                File savePath = new File(rootDir + uploadDir + autoCreatedDateDir);
                if (!savePath.exists()) {
                    savePath.mkdirs();
                }

                String fileName = savePath + "/" + fileId;

                BlobItem dataFile = new BlobItemEntity();
                dataFile.setLastModified(System.currentTimeMillis());
                dataFile.setCreateBy(loginContext.getActorId());
                dataFile.setFileId(fileId);
                dataFile.setPath(uploadDir + autoCreatedDateDir + "/" + fileId);
                dataFile.setFilename(mFile.getOriginalFilename());
                dataFile.setName(mFile.getOriginalFilename());
                dataFile.setContentType(mFile.getContentType());
                dataFile.setType(type);
                dataFile.setStatus(0);
                dataFile.setServiceKey(serviceKey);
                if (mFile.getSize() <= maxDiskSize) {
                    dataFile.setData(mFile.getBytes());
                }
                blobService.insertBlob(dataFile);
                dataFile.setData(null);

                if (mFile.getSize() > maxDiskSize) {
                    FileUtils.save(fileName, inputStream);
                    logger.debug(fileName + " save ok.");
                }

                if (StringUtils.equalsIgnoreCase(responseType, "json")) {
                    StringBuilder json = new StringBuilder();
                    json.append("{");
                    json.append("'");
                    json.append("fileId");
                    json.append("':'");
                    json.append(fileId);
                    json.append("'");
                    Enumeration<String> pNames = request.getParameterNames();
                    String pName;
                    while (pNames.hasMoreElements()) {
                        json.append(",");
                        pName = (String) pNames.nextElement();
                        json.append("'");
                        json.append(pName);
                        json.append("':'");
                        json.append(request.getParameter(pName));
                        json.append("'");
                    }
                    json.append("}");
                    logger.debug(json.toString());
                    response.getWriter().write(json.toString());
                } else {
                    out.print(fileId);
                }
            }
        }

    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        IOUtils.close(inputStream);
    }
}

From source file:gr.abiss.calipso.tiers.controller.AbstractModelWithAttachmentsController.java

@ApiOperation(value = "Add a file uploads to property")
@RequestMapping(value = "{subjectId}/uploads/{propertyName}", method = { RequestMethod.POST,
        RequestMethod.PUT }, consumes = {})
public @ResponseBody BinaryFile addUploadsToProperty(@PathVariable ID subjectId,
        @PathVariable String propertyName, MultipartHttpServletRequest request, HttpServletResponse response) {
    LOGGER.info("uploadPost called");

    Configuration config = ConfigurationFactory.getConfiguration();
    String fileUploadDirectory = config.getString(ConfigurationFactory.FILES_DIR);
    String baseUrl = config.getString("calipso.baseurl");

    Iterator<String> itr = request.getFileNames();
    MultipartFile mpf;
    BinaryFile bf = new BinaryFile();
    try {//from  w w  w  .  ja v a2s.c o  m
        if (itr.hasNext()) {

            mpf = request.getFile(itr.next());
            LOGGER.info("Uploading {}", mpf.getOriginalFilename());

            bf.setName(mpf.getOriginalFilename());
            bf.setFileNameExtention(
                    mpf.getOriginalFilename().substring(mpf.getOriginalFilename().lastIndexOf(".") + 1));

            bf.setContentType(mpf.getContentType());
            bf.setSize(mpf.getSize());

            // request targets specific path?
            StringBuffer uploadsPath = new StringBuffer('/')
                    .append(this.service.getDomainClass().getDeclaredField("PATH_FRAGMENT").get(String.class))
                    .append('/').append(subjectId).append("/uploads/").append(propertyName);
            bf.setParentPath(uploadsPath.toString());
            LOGGER.info("Saving image entity with path: " + bf.getParentPath());
            bf = binaryFileService.create(bf);

            LOGGER.info("file name: {}", bf.getNewFilename());
            bf = binaryFileService.findById(bf.getId());
            LOGGER.info("file name: {}", bf.getNewFilename());

            File storageDirectory = new File(fileUploadDirectory + bf.getParentPath());

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

            LOGGER.info("storageDirectory: {}", storageDirectory.getAbsolutePath());
            LOGGER.info("file name: {}", bf.getNewFilename());

            File newFile = new File(storageDirectory, bf.getNewFilename());
            newFile.createNewFile();
            LOGGER.info("newFile path: {}", newFile.getAbsolutePath());
            Files.copy(mpf.getInputStream(), newFile.toPath(), StandardCopyOption.REPLACE_EXISTING);

            BufferedImage thumbnail = Scalr.resize(ImageIO.read(newFile), 290);
            File thumbnailFile = new File(storageDirectory, bf.getThumbnailFilename());
            ImageIO.write(thumbnail, "png", thumbnailFile);
            bf.setThumbnailSize(thumbnailFile.length());

            bf = binaryFileService.update(bf);

            // attach file
            // TODO: add/update to collection
            Field fileField = GenericSpecifications.getField(this.service.getDomainClass(), propertyName);
            Class clazz = fileField.getType();
            if (BinaryFile.class.isAssignableFrom(clazz)) {
                T target = this.service.findById(subjectId);
                BeanUtils.setProperty(target, propertyName, bf);
                this.service.update(target);
            }

            bf.setUrl(baseUrl + "/api/rest/" + bf.getParentPath() + "/files/" + bf.getId());
            bf.setThumbnailUrl(baseUrl + "/api/rest/" + bf.getParentPath() + "/thumbs/" + bf.getId());
            bf.setDeleteUrl(baseUrl + "/api/rest/" + bf.getParentPath() + "/" + bf.getId());
            bf.setDeleteType("DELETE");
            bf.addInitialPreview("<img src=\"" + bf.getThumbnailUrl() + "\" class=\"file-preview-image\" />");

        }

    } catch (Exception e) {
        LOGGER.error("Could not upload file(s) ", e);
    }

    return bf;
}

From source file:cn.orignzmn.shopkepper.common.utils.excel.ImportExcel.java

/**
 * //from   www  . ja va2 s  . c  om
 * @param file 
 * @param headerNum ???=?+1
 * @param sheetIndex ?
 * @throws InvalidFormatException 
 * @throws IOException 
 */
public ImportExcel(MultipartFile multipartFile, int headerNum, int sheetIndex)
        throws InvalidFormatException, IOException {
    this(multipartFile.getOriginalFilename(), multipartFile.getInputStream(), headerNum, sheetIndex);
}

From source file:com.ace.erp.controller.sys.company.OrganizationController.java

@RequestMapping(value = "/company/upload", method = RequestMethod.POST)
@ResponseBody/* w  w  w  .j  a  v a  2  s .  c o  m*/
public Response upload(@CurrentUser User user, String srcFile, MultipartHttpServletRequest request,
        HttpServletResponse response) {

    try {
        MultipartFile realPicFile = request.getFile(srcFile);
        InputStream in = realPicFile.getInputStream();
        String path = request.getSession().getServletContext().getRealPath("/");
        String fileName = user.getUsername() + "."
                + FilenameUtils.getExtension(realPicFile.getOriginalFilename());
        File f = new File(path + "/" + fileName);
        FileUtils.copyInputStreamToFile(in, f);
        logger.info("path : " + f.getAbsolutePath());
    } catch (Exception e) {
        logger.error("upload header picture error : ", e);
    }
    return null;
}

From source file:io.onedecision.engine.decisions.web.DecisionDmnModelController.java

/**
 * Upload DMN representation of decision.
 * /*from   w  w w.j  a  va2  s  .c om*/
 * @param files
 *            DMN files posted in a multi-part request and optionally an
 *            image of it.
 * @return The model created in the repository.
 * @throws IOException
 *             If cannot parse the file.
 */
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public @ResponseBody DmnModel handleFileUpload(@PathVariable("tenantId") String tenantId,
        @RequestParam(value = "deploymentMessage", required = false) String deploymentMessage,
        @RequestParam(value = "file", required = true) MultipartFile... files) throws IOException {
    LOGGER.info(String.format("Uploading dmn for: %1$s", tenantId));

    if (files.length > 2) {
        throw new IllegalArgumentException(String
                .format("Expected one DMN file and optionally one image file but received %1$d", files.length));
    }

    String dmnContent = null;
    String dmnFileName = null;
    byte[] image = null;
    for (MultipartFile resource : files) {
        LOGGER.debug(String.format("Deploying file: %1$s", resource.getOriginalFilename()));
        if (resource.getOriginalFilename().toLowerCase().endsWith(".dmn")
                || resource.getOriginalFilename().toLowerCase().endsWith(".dmn.xml")) {
            LOGGER.debug("... DMN resource");
            dmnContent = new String(resource.getBytes(), "UTF-8");
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("DMN: " + dmnContent);
            }
            dmnFileName = resource.getOriginalFilename();
        } else {
            LOGGER.debug("... non-DMN resource");
            image = resource.getBytes();
        }
    }

    if (dmnContent == null) {
        throw new NoDmnFileInUploadException();
    }
    if (deploymentMessage == null || deploymentMessage.length() == 0) {
        deploymentMessage = String.format("Deployed from file: %1$s", dmnFileName);
    }
    DmnModel dmnModel = new DmnModel(dmnContent, deploymentMessage, image, tenantId);
    dmnModel.setName(IdHelper.toName(dmnFileName));
    dmnModel.setDefinitionXml(dmnContent);
    return createModelForTenant(dmnModel);
}

From source file:de.iteratec.iteraplan.presentation.dialog.ExcelImport.ImportFrontendServiceImpl.java

private boolean handleTimeseriesFile(MassdataMemBean memBean, MultipartFile file) {
    memBean.resetResultMessages();//from   w  w w  . jav a 2 s. c  o m
    if (file == null || file.getSize() == 0) {
        memBean.addErrorMessage(MessageAccess.getString("import.no.file"));
        return false;
    }

    String originalFilename = file.getOriginalFilename();
    memBean.setFileName(originalFilename);

    if (!hasAcceptableExcelFileExtension(originalFilename)) {
        memBean.setImportType(null);
        memBean.setFileContent(null);
        memBean.addErrorMessage(MessageAccess.getString("import.wrong.type"));
        return false;
    }

    memBean.setImportType(ImportType.EXCEL);
    setFileContentToMemBean(memBean, file);
    return true;
}