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:apiserver.services.images.controllers.MetadataController.java

/**
 * get embedded metadata//from w w  w  . j av  a2  s  .  c o m
 * @param file uploaded image
 * @return   height,width
 */
@ApiOperation(value = "Get the embedded metadata", responseClass = "java.util.Map")
@RequestMapping(value = "/info/metadata", method = { RequestMethod.POST })
public WebAsyncTask<Map> imageMetadataByImage(
        @ApiParam(name = "file", required = true) @RequestParam(value = "file", required = true) MultipartFile file) {
    final MultipartFile _file = file;

    Callable<Map> callable = new Callable<Map>() {
        @Override
        public Map call() throws Exception {
            FileMetadataJob job = new FileMetadataJob();
            job.setDocumentId(null);
            job.setDocument(new Document(_file));
            job.getDocument().setContentType(MimeType.getMimeType(_file.getContentType()));
            job.getDocument().setFileName(_file.getOriginalFilename());

            Future<Map> imageFuture = imageMetadataGateway.getMetadata(job);
            FileMetadataJob payload = (FileMetadataJob) imageFuture.get(defaultTimeout, TimeUnit.MILLISECONDS);

            return payload.getMetadata();
        }
    };

    return new WebAsyncTask<Map>(defaultTimeout, callable);
}

From source file:com.vsquaresystem.safedeals.location.LocationService.java

@Transactional(readOnly = false)
public Boolean insertAttachments(MultipartFile attachmentMultipartFile)
        throws JsonProcessingException, IOException {
    logger.info("attachmentMultipartFile in service Line31{}", attachmentMultipartFile);
    System.out.println("attachmentMultipartFile" + attachmentMultipartFile);
    File outputFile = attachmentUtils.storeAttachmentByAttachmentType(
            attachmentMultipartFile.getOriginalFilename(), attachmentMultipartFile.getInputStream(),
            AttachmentUtils.AttachmentType.LOCATION);
    return outputFile.exists();
}

From source file:service.ArticleService.java

public ServiceResult update(Article obj, MultipartFile file, boolean deleteFile) throws IOException {
    ServiceResult res = new ServiceResult();

    if (deleteFile) {
        delFile(obj.getArticleId());// w  w  w.ja v a  2 s.  com
    }

    res = validateUpdate(obj, dao);

    if (file != null && !file.isEmpty()) {
        delFile(obj.getArticleId());

        ArticleFile newFileEnt = new ArticleFile();
        newFileEnt.setArticle(obj);
        newFileEnt.setRusname(file.getOriginalFilename());
        saveFile(newFileEnt, file);
    }
    return res;
}

From source file:pt.ist.fenix.ui.spring.PagesAdminService.java

@Atomic(mode = Atomic.TxMode.WRITE)
protected GroupBasedFile addAttachment(String name, MultipartFile attachment, MenuItem menuItem)
        throws IOException {
    Post post = postForPage(menuItem.getPage());
    GroupBasedFile file = new GroupBasedFile(name, attachment.getOriginalFilename(), attachment.getBytes(),
            AnyoneGroup.get());/*  w  w w .  j av  a 2 s. com*/
    post.getAttachments().putFile(file, 0);
    return file;
}

From source file:com.dlshouwen.wzgl.album.controller.AlbumController.java

/**
 * /*from  ww w . j  a  v a2  s  .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;
    }
    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
    MultipartFile multipartFile = multipartRequest.getFile("picture");
    String fileName = multipartFile.getOriginalFilename();
    //?
    String path = null;
    if (null != multipartFile && StringUtils.isNotEmpty(multipartFile.getOriginalFilename())) {
        JSONObject jobj = FileUploadClient.upFile(request, fileName, multipartFile.getInputStream());
        if (jobj.getString("responseMessage").equals("OK")) {
            path = jobj.getString("fpath");
        }
    }
    /*
    if (fileName.trim().length() > 0) {
    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();
        }
    }
    path = path.replaceAll("\\\\", "/");
    album.setAlbum_coverpath(path);
    }
    */
    if (null != path) {
        album.setAlbum_coverpath(path);
    }
    //      ????
    Date nowDate = new Date();
    //      ?
    album.setAlbum_updatedate(nowDate);
    album.setAlbum_flag("1");
    //      
    dao.updateAlbum(album);
    //      ????
    ajaxResponse.setSuccess(true);
    ajaxResponse.setSuccessMessage("??");
    //?
    Map map = new HashMap();
    map.put("URL", basePath + "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.xumpy.thuisadmin.controllers.pages.Finances.java

@RequestMapping(value = "/finances/nieuwBedragDocument/saveDocument", method = RequestMethod.POST)
public String saveBedragDocument(@ModelAttribute("document") NieuwDocument document,
        @RequestParam("file") MultipartFile file) throws IOException {
    DocumentenSrvPojo bedragDocument = new DocumentenSrvPojo();

    bedragDocument.setBedrag(new BedragenSrvPojo(bedragenSrv.findBedrag(document.getBedrag_id())));
    //bedragDocument.setDatum(document.getDatum());
    bedragDocument.setDocument(file.getBytes());
    bedragDocument.setDocument_mime(file.getContentType());
    bedragDocument.setDocument_naam(file.getOriginalFilename());
    bedragDocument.setOmschrijving(document.getOmschrijving());
    bedragDocument.setPk_id(document.getPk_id());

    Log.info("File bytes: " + file.getBytes().length);
    Log.info("Document PK_ID: " + document.getPk_id());

    if (file.getBytes().length == 0 && document.getPk_id() != null) {
        Documenten bedragDocumentOld = documentenSrv.fetchDocument(document.getPk_id());
        bedragDocument.setDocument(bedragDocumentOld.getDocument());
        bedragDocument.setDocument_mime(bedragDocumentOld.getDocument_mime());
        bedragDocument.setDocument_naam(bedragDocumentOld.getDocument_naam());
    }//from ww w  . j a  v a  2  s.  c  o  m

    documentenSrv.save(bedragDocument);

    return "redirect:/finances/nieuwBedrag/" + document.getBedrag_id();
}

From source file:org.zols.documents.service.DocumentService.java

/**
 * Upload documents/*from   ww  w . j  a  v  a 2  s . co  m*/
 *
 * @param documentRepositoryName name of the repository
 * @param upload documents to be uploaded
 * @param rootFolderPath source path of the document
 */
public void upload(String documentRepositoryName, Upload upload, String rootFolderPath)
        throws DataStoreException {
    DocumentRepository documentRepository = documentRepositoryService.read(documentRepositoryName);
    String folderPath = documentRepository.getPath();
    if (rootFolderPath != null && rootFolderPath.trim().length() != 0) {
        folderPath = folderPath + File.separator + rootFolderPath;
    }
    List<MultipartFile> multipartFiles = upload.getFiles();
    if (null != multipartFiles && multipartFiles.size() > 0) {
        for (MultipartFile multipartFile : multipartFiles) {
            //Handle file content - multipartFile.getInputStream()
            byte[] bytes;
            try {
                bytes = multipartFile.getBytes();

                BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(
                        new File(folderPath + File.separator + multipartFile.getOriginalFilename())));
                stream.write(bytes);
                stream.close();
            } catch (IOException ex) {
                java.util.logging.Logger.getLogger(DocumentService.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}

From source file:cn.org.once.cstack.service.impl.ModuleServiceImpl.java

@Override
public String runScript(String moduleName, MultipartFile file) throws ServiceException {
    try {/*from  w ww. ja v a 2s. co m*/
        Module module = findByName(moduleName);

        String filename = file.getOriginalFilename();
        String containerId = module.getContainerID();
        String tempDirectory = dockerService.getEnv(containerId, "CU_TMP");
        fileService.sendFileToContainer(containerId, tempDirectory, file, null, null);

        @SuppressWarnings("serial")
        Map<String, String> kvStore = new HashMap<String, String>() {
            {
                put("CU_FILE", filename);
            }
        };
        return dockerService.execCommand(containerId, RemoteExecAction.RUN_SCRIPT.getCommand(kvStore));
    } catch (Exception e) {
        throw new ServiceException(e.getLocalizedMessage(), e);
    }
}

From source file:com.dlshouwen.wzgl.album.controller.AlbumController.java

/**
 * //  w w  w .ja  v  a2  s. co  m
 *
 * @param album 
 * @param bindingResult 
 * @param request 
 * @return ajax?
 * @throws Exception 
 */
@RequestMapping(value = "/add", method = RequestMethod.POST)
public void addAlbum(@Valid Album album, BindingResult bindingResult, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    AjaxResponse ajaxResponse = new AjaxResponse();

    if (bindingResult.hasErrors()) {
        ajaxResponse.bindingResultHandler(bindingResult);
        LogUtils.updateOperationLog(request, OperationType.INSERT,
                "??" + album.getAlbum_name() + "?"
                        + AjaxResponse.getBindingResultMessage(bindingResult) + "");
        response.setContentType("text/html;charset=utf-8");
        JSONObject obj = JSONObject.fromObject(ajaxResponse);
        response.getWriter().write(obj.toString());
        return;
    }
    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
    MultipartFile multipartFile = multipartRequest.getFile("picture");
    String fileName = multipartFile.getOriginalFilename();
    //?
    String path = null;
    if (null != multipartFile && StringUtils.isNotEmpty(multipartFile.getOriginalFilename())) {
        JSONObject jobj = FileUploadClient.upFile(request, fileName, multipartFile.getInputStream());
        if (jobj.getString("responseMessage").equals("OK")) {
            path = jobj.getString("fpath");
        }
    }
    /*
    if (fileName.trim().length() > 0) {
    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();
        }
    }
    path = path.replaceAll("\\\\", "/");
    album.setAlbum_coverpath(path);
    }
    */
    if (null != path) {
        album.setAlbum_coverpath(path);
    }
    //      ????
    SessionUser sessionUser = (SessionUser) request.getSession().getAttribute(CONFIG.SESSION_USER);
    String userName = sessionUser.getUser_name();
    String userId = sessionUser.getUser_id();
    Date nowDate = new Date();
    //      ?????
    album.setAlbum_id(new GUID().toString());
    album.setAlbum_createuser(userName);
    album.setAlbum_createuserbyid(userId);
    album.setAlbum_createdate(nowDate);

    //      
    dao.insertAlbum(album);
    //      ????
    ajaxResponse.setSuccess(true);
    ajaxResponse.setSuccessMessage("??");
    //?
    Map map = new HashMap();
    map.put("URL", basePath + "album");
    ajaxResponse.setExtParam(map);

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

From source file:apiserver.services.images.controllers.ImageController.java

/**
 * get basic info about image./*from w  ww. ja  v a  2  s .  c om*/
 * @param file
 * @return
 * @throws java.util.concurrent.ExecutionException
 * @throws java.util.concurrent.TimeoutException
 * @throws InterruptedException
 */
@ApiOperation(value = "Get the height and width for the image", responseClass = "java.util.Map")
@RequestMapping(value = "/info/size", method = { RequestMethod.POST })
public WebAsyncTask<Map> imageInfoByImageAsync(
        @ApiParam(name = "file", required = true) @RequestParam(value = "file", required = true) MultipartFile file)
        throws ExecutionException, TimeoutException, InterruptedException {
    final MultipartFile _file = file;

    Callable<Map> callable = new Callable<Map>() {
        @Override
        public Map call() throws Exception {
            FileInfoJob job = new FileInfoJob();
            job.setDocumentId(null);
            job.setDocument(new Document(_file));
            job.getDocument().setContentType(MimeType.getMimeType(_file.getContentType()));
            job.getDocument().setFileName(_file.getOriginalFilename());

            Future<Map> imageFuture = gateway.imageSize(job);
            Map payload = imageFuture.get(defaultTimeout, TimeUnit.MILLISECONDS);

            return payload;
        }
    };

    return new WebAsyncTask<Map>(defaultTimeout, callable);
}