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

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

Introduction

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

Prototype

@Override
InputStream getInputStream() throws IOException;

Source Link

Document

Return an InputStream to read the contents of the file from.

Usage

From source file:org.exem.flamingo.web.filesystem.hdfs.HdfsBrowserController.java

/**
 * ?  ?? HDFS ? .//  w  w w  . ja  v  a 2 s . c  o m
 *
 * @return REST Response JAXB Object
 */
@RequestMapping(value = "upload", method = RequestMethod.POST, consumes = { "multipart/form-data" })
@ResponseStatus(HttpStatus.OK)
public ResponseEntity<String> upload(HttpServletRequest req) throws IOException {
    Response response = new Response();

    if (!(req instanceof DefaultMultipartHttpServletRequest)) {
        response.setSuccess(false);
        response.getError().setCause("Request is not a file upload.");
        response.getError().setMessage("Failed to upload a file.");
        String json = new ObjectMapper().writeValueAsString(response);
        return new ResponseEntity(json, HttpStatus.BAD_REQUEST);
    }

    InputStream inputStream;
    DefaultMultipartHttpServletRequest request = (DefaultMultipartHttpServletRequest) req;

    String username = SessionUtils.getUsername();
    String dstPath = request.getParameter("dstPath");
    MultipartFile uploadedFile = request.getFile("fileName");
    String originalFilename = uploadedFile.getOriginalFilename();
    String pathToUpload = getPathFilter(dstPath);
    String fullyQualifiedPath = pathToUpload.equals("/") ? pathToUpload + originalFilename
            : pathToUpload + SystemUtils.FILE_SEPARATOR + originalFilename;

    inputStream = uploadedFile.getInputStream();

    //TODO HDFS  ? ? 
    /*List<String> paths = hdfsBrowserAuthService.getHdfsBrowserPatternAll(username);
    String hdfsPathPattern = hdfsBrowserAuthService.validateHdfsPathPattern(pathToUpload, paths);
            
    Map fileMap = new HashMap();
    fileMap.put("username", username);
    fileMap.put("hdfsPathPattern", hdfsPathPattern);
    fileMap.put("condition", "uploadFile");
    hdfsBrowserAuthService.getHdfsBrowserUserDirAuth(fileMap);*/

    // Engine? Remote?  ?.
    boolean isRemoteEngine = Boolean.parseBoolean(isRemote);

    // Remote ? ? ?, Remote? Store and Forward 
    if (!isRemoteEngine) {

        fileSystemService.validatePath(pathToUpload);

        String namenodeAgentUrl = MessageFormatter
                .arrayFormat("http://{}:{}/remote/agent/transfer/upload?fullyQualifiedPath={}&username={}",
                        new Object[] { namenodeAgentAddress, namenodeAgentPort,
                                URLEncoder.encode(fullyQualifiedPath, "UTF-8"), username })
                .getMessage();

        HttpPost httpPost = new HttpPost(namenodeAgentUrl);
        HttpEntity reqEntity = new InputStreamEntity(inputStream);
        httpPost.setEntity(reqEntity);
        HttpResponse execute = httpClient.execute(httpPost);

        if (execute.getStatusLine().getStatusCode() == 500) {
            response.setSuccess(false);
            response.getError().setMessage("?? ?? .");
        } else if (execute.getStatusLine().getStatusCode() == 600) {
            response.setSuccess(false);
            response.getError().setMessage("(/) ?   .");
        } else {
            response.setSuccess(true);
        }

        inputStream.close();
        httpPost.releaseConnection();
    } else {
        boolean saved;
        byte[] bytes = FileCopyUtils.copyToByteArray(inputStream);
        fileSystemService.validateBeforeUpload(pathToUpload, fullyQualifiedPath, bytes, username);
        saved = fileSystemService.save(pathToUpload, fullyQualifiedPath, bytes, username);
        response.setSuccess(saved);
    }

    response.getMap().put("directory", pathToUpload);
    String json = new ObjectMapper().writeValueAsString(response);
    HttpStatus statusCode = HttpStatus.OK;

    return new ResponseEntity(json, statusCode);
}

From source file:org.onebusaway.nyc.vehicle_tracking.webapp.controllers.VehicleLocationSimulationController.java

@RequestMapping(value = "/vehicle-location-simulation!upload-trace.do", method = RequestMethod.POST)
public ModelAndView uploadTrace(@RequestParam("file") MultipartFile file,
        @RequestParam(value = "realtime", required = false, defaultValue = "false") boolean realtime,
        @RequestParam(value = "pauseOnStart", required = false, defaultValue = "false") boolean pauseOnStart,
        @RequestParam(value = "shiftStartTime", required = false, defaultValue = "false") boolean shiftStartTime,
        @RequestParam(value = "minimumRecordInterval", required = false, defaultValue = "0") int minimumRecordInterval,
        @RequestParam(value = "traceType", required = true) String traceType,
        @RequestParam(required = false, defaultValue = "false") boolean bypassInference,
        @RequestParam(required = false, defaultValue = "false") boolean fillActualProperties,
        @RequestParam(value = "loop", required = false, defaultValue = "false") boolean loop,
        @RequestParam(required = false, defaultValue = "false") boolean returnId) throws IOException {

    int taskId = -1;

    if (!file.isEmpty()) {

        String name = file.getOriginalFilename();
        InputStream in = file.getInputStream();

        if (name.endsWith(".gz"))
            in = new GZIPInputStream(in);

        taskId = _vehicleLocationSimulationService.simulateLocationsFromTrace(traceType, in, realtime,
                pauseOnStart, shiftStartTime, minimumRecordInterval, bypassInference, fillActualProperties,
                loop);/*from ww w.ja v a2  s  . c o m*/
    }

    if (returnId) {
        return new ModelAndView("vehicle-location-simulation-taskId.jspx", "taskId", taskId);
    } else {
        return new ModelAndView("redirect:/vehicle-location-simulation.do");
    }
}

From source file:com.wavemaker.studio.StudioService.java

@ExposeToClient
public FileUploadResponse uploadJar(MultipartFile file) {
    FileUploadResponse ret = new FileUploadResponse();
    try {// www. j av  a  2s  .  c  om
        String filename = file.getOriginalFilename();
        String filenameExtension = StringUtils.getFilenameExtension(filename);
        if (!StringUtils.hasLength(filenameExtension)) {
            throw new IOException("Please upload a jar file");
        }
        if (!"jar".equals(filenameExtension)) {
            throw new IOException("Please upload a jar file, not a " + filenameExtension + " file");
        }
        Folder destinationFolder = this.fileSystem.getStudioWebAppRootFolder().getFolder("WEB-INF/lib");
        File destinationFile = destinationFolder.getFile(filename);
        destinationFile.getContent().write(file.getInputStream());
        ret.setPath(destinationFile.getName());

        // Copy jar to common/lib in WaveMaker Home
        Folder commonLib = fileSystem.getWaveMakerHomeFolder().getFolder(CommonConstants.COMMON_LIB);
        commonLib.createIfMissing();
        File destinationJar = commonLib.getFile(filename);
        destinationJar.getContent().write(file.getInputStream());

        // Copy jar to project's lib
        com.wavemaker.tools.io.ResourceFilter included = FilterOn.antPattern("*.jar");
        commonLib.find().include(included).files()
                .copyTo(this.projectManager.getCurrentProject().getRootFolder().getFolder("lib"));
    } catch (IOException e) {
        ret.setError(e.getMessage());
    }
    return ret;
}

From source file:org.dspace.app.webui.cris.controller.ImportFormController.java

@Override
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command,
        BindException errors) throws Exception {
    Context dspaceContext = UIUtil.obtainContext(request);

    ImportDTO object = (ImportDTO) command;
    MultipartFile fileDTO = object.getFile();

    // read folder from configuration and make dir
    String path = ConfigurationManager.getProperty(CrisConstants.CFG_MODULE, "researcherpage.file.import.path");
    File dir = new File(path);
    dir.mkdir();/*from  w w w.j  a va  2 s . c o  m*/
    try {
        if (object.getModeXSD() != null) {
            response.setContentType("application/xml;charset=UTF-8");
            response.addHeader("Content-Disposition", "attachment; filename=rp.xsd");
            String nameXSD = "xsd-download-webuirequest.xsd";
            File filexsd = new File(dir, nameXSD);
            filexsd.createNewFile();
            ImportExportUtils.generateXSD(response.getWriter(), dir,
                    applicationService.findAllContainables(RPPropertiesDefinition.class), filexsd, null);
            response.getWriter().flush();
            response.getWriter().close();
            return null;
        } else {
            if (fileDTO != null && !fileDTO.getOriginalFilename().isEmpty()) {
                Boolean defaultStatus = ConfigurationManager.getBooleanProperty(CrisConstants.CFG_MODULE,
                        "researcherpage.file.import.rpdefaultstatus");
                if (AuthorizeManager.isAdmin(dspaceContext)) {
                    dspaceContext.turnOffAuthorisationSystem();
                }
                ImportExportUtils.importResearchersXML(fileDTO.getInputStream(), dir, applicationService,
                        dspaceContext, defaultStatus);
                saveMessage(request, getText("action.import.with.success", request.getLocale()));
            }
        }
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        saveMessage(request, getText("action.import.with.noSuccess", e.getMessage(), request.getLocale()));
    }

    return new ModelAndView(getSuccessView());

}

From source file:com.wonders.bud.freshmommy.web.content.controller.ContentController.java

/**
 * <p>/* ww w  .j  a v a  2 s.co m*/
 * Description:[]
 * </p>
 * Created by [HYH] [20141128] Midified by [] []
 * 
 * @param request
 * @param response
 * @param session
 * @return
 * @throws Exception
 * @throws IOException
 */
@RequestMapping(value = "/video", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<RestMsg<String>> video(HttpServletRequest request, HttpServletResponse response,
        HttpSession session) throws Exception, IOException {

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.TEXT_PLAIN);
    // MultipartHttpRequest
    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
    // 
    MultipartFile file = multipartRequest.getFile("videofile");
    RestMsg<String> rm = new RestMsg<String>();
    String fileType = file.getContentType();
    if (fileType.toLowerCase().indexOf("video") < 0) {
        rm = rm.errorMsg();
        rm.setMsg("??");
        return new ResponseEntity<RestMsg<String>>(rm, headers, HttpStatus.OK);
    }
    // ??
    String filename = file.getOriginalFilename();
    String[] temp1 = filename.split("\\.");
    String extenName = temp1[temp1.length - 1];
    StringBuffer fileNameBuffer = new StringBuffer();
    fileNameBuffer.append(UUID.randomUUID()).append(".").append(extenName);

    InputStream input = file.getInputStream();
    String actionPath = request.getSession().getServletContext().getRealPath("");
    String path = actionPath + File.separator + CONTENT_TEMP_FILE;
    File savePath = new File(path);
    if (!savePath.exists()) { // 
        savePath.mkdir();
    }
    FileUtil.SaveFileFromInputStream(input, savePath.toString(), fileNameBuffer.toString());
    String filePath = "temps/" + fileNameBuffer;
    rm = rm.successMsg();
    rm.setResult(filePath);
    return new ResponseEntity<RestMsg<String>>(rm, headers, HttpStatus.OK);
}

From source file:argendata.web.controller.DatasetController.java

@RequestMapping(method = RequestMethod.POST)
public ModelAndView bulkUpload(HttpSession session, BulkUploadForm bulkUploadForm, Errors err) {

    MultipartFile file = null;
    ModelAndView mav = new ModelAndView();

    file = bulkUploadForm.getFile();//from w w  w.  java  2  s.  com

    validatorBulkUpload.validate(bulkUploadForm, err);
    if (err.hasErrors()) {
        return mav;
    }

    String error = null;

    if (file.isEmpty()) {

        logger.error("Escriba una ruta valida!");
        error = "Error. El archivo esta vacio.";
        mav.addObject("error", error);
        return mav;
    }

    int count = 0;

    /*
     * Titulo, Licencia, Tags (Separadas con ;),Calidad de la inforamcin,
     * Modificado, Granularidad Geografica, Granularidad Temporal,
     * Publicante, URL de Acceso, Tamao, Formato, Tipo de Distribucion,
     * locacion, descripcion
     */

    try {
        InputStream inputStream = file.getInputStream();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

        String line;

        while ((line = bufferedReader.readLine()) != null) {
            if (line.isEmpty() || line.startsWith("#")) {
                continue; // es comentario o line en blanco
            }

            String[] attrs = line.split(";");

            if (attrs.length < 12) {
                throw new Exception("Linea " + (count + 1) + " mal formada.");
            }
            /* Titulo */
            String title = attrs[0].trim();

            /* Licence */
            String license = attrs[1].trim();

            /* Tags */
            Set<String> tags = new HashSet<String>();
            String[] items = attrs[2].split(",");
            int cantTags = 0;
            logger.debug(items.length);
            while (cantTags < items.length) {
                tags.add(items[cantTags].trim());
                cantTags++;
            }

            /* Quality of the Information */
            String qualityOfInformation = attrs[3].trim();
            if (!(qualityOfInformation.equals("Baja") || qualityOfInformation.equals("Media")
                    || qualityOfInformation.equals("Alta"))) {
                throw new Exception("Linea " + (count + 1) + " mal formada, calidad de informacion invalida");
            }

            /* Modify */
            String[] sels = attrs[4].split("-");

            if (sels.length < 3) {
                throw new Exception("Fecha invalidad en la linea " + (count + 1));
            }

            String yearModify = sels[0];
            String monthModify = sels[1];
            String dayModify = sels[2];

            dayModify = dayModify.length() == 1 ? "0" + dayModify : dayModify;
            monthModify = monthModify.length() == 1 ? "0" + monthModify : monthModify;

            /*
             * Date fechaModificado = Date.valueOf(anioModificado + "-" +
             * mesModificado + "-" + diaModificado);
             */
            // String fechaModificado = diaModificado + "-" + mesModificado
            // + "-" + anioModificado;
            String dateModify = yearModify + "-" + monthModify + "-" + dayModify + "T23:59:59Z";
            // String fechaModificado = "1995-12-31T23:59:59Z";
            /* Granularidad Geografica */
            String granuGeogra = attrs[5].trim();

            /* Granularidad Temporal */
            String granuTemporal = attrs[6].trim();

            /* Publicante */
            String publicante = attrs[7].trim();
            Organization miPublicante = new Organization();
            miPublicante.setName(publicante);
            miPublicante.setNameId(Parsing.withoutSpecialCharacters(publicante));

            /* URL de Acceso */
            String url = attrs[8].trim();

            /* Tamao */
            String tamanio = attrs[9].trim();

            /* Formato */
            String formato = attrs[10].trim();

            /* Tipo de Distribucion */
            Distribution distribution;

            String tipoDistribucion = attrs[11].trim();
            if (tipoDistribucion.equals("Feed")) {
                distribution = new Feed();
            } else if (tipoDistribucion.equals("Download")) {
                distribution = new Download();
            } else if (tipoDistribucion.equals("Web Service")) {
                distribution = new WebService();
            } else {
                throw new Exception("Linea " + (count + 1) + " mal formada, tipo informacion invalida");
            }
            distribution.setAccessURL(url);
            distribution.setFormat(formato);
            distribution.setSize(new Integer(tamanio));

            /* Locacion */
            String location = attrs[12].trim();
            if (location.equals("")) {
                location = "Desconocida";
            }

            /* Descripcion */
            String description = "";
            for (int i = 13; i < attrs.length; i++) {
                description = description + attrs[i];
                if (i != attrs.length - 1) {
                    description = description + "; ";
                }
            }

            Dataset aDataset = new Dataset(title, description, license, tags, qualityOfInformation, dateModify,
                    granuGeogra, granuTemporal, location, miPublicante, distribution,
                    Parsing.withoutSpecialCharacters(title));

            if (!datasetService.existApprovedDataset(title)) {
                datasetService.store(aDataset);
                count++;
            }
        }
    } catch (Exception a) {
        logger.error("Error en la carga masiva.");
        logger.error(a.getMessage(), a);
        error = a.getMessage();
        count = 0;
        mav.addObject("error", error);

    }

    if (count > 0) {
        mav.addObject("info", "Agrego " + count + " dataset's exitosamente.");
    }

    if (count == 0) {
        mav.addObject("info", "No haba datasets nuevos para agregar.");
    }
    return mav;
}

From source file:com.wonders.bud.freshmommy.web.content.controller.ContentController.java

/**
 * audiofile/*from w w  w . ja v a2 s . co  m*/
 * <p>
 * Description:[]
 * </p>
 * Created by [HYH] [20141128] Midified by [] []
 * 
 * @param request
 * @param response
 * @param session
 * @return
 * @throws Exception
 * @throws IOException
 */
@RequestMapping(value = "/audio", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<RestMsg<String>> audio(HttpServletRequest request, HttpServletResponse response,
        HttpSession session) throws Exception, IOException {

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.TEXT_PLAIN);
    // MultipartHttpRequest
    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
    // 
    MultipartFile file = multipartRequest.getFile("audiofile");
    RestMsg<String> rm = new RestMsg<String>();
    String fileType = file.getContentType();
    if ((fileType.toLowerCase().indexOf("audio") < 0)) {
        rm = rm.errorMsg();
        rm.setMsg("??");
        return new ResponseEntity<RestMsg<String>>(rm, headers, HttpStatus.OK);
    }
    // ??
    String filename = file.getOriginalFilename();
    String[] temp1 = filename.split("\\.");
    String extenName = temp1[temp1.length - 1];
    StringBuffer fileNameBuffer = new StringBuffer();
    fileNameBuffer.append(UUID.randomUUID()).append(".").append(extenName);

    InputStream input = file.getInputStream();
    String actionPath = request.getSession().getServletContext().getRealPath("");
    String path = actionPath + File.separator + CONTENT_TEMP_FILE;
    File savePath = new File(path);
    if (!savePath.exists()) { // 
        savePath.mkdir();
    }
    FileUtil.SaveFileFromInputStream(input, savePath.toString(), fileNameBuffer.toString());
    String filePath = "temps/" + fileNameBuffer;
    rm = rm.successMsg();
    rm.setResult(filePath);
    return new ResponseEntity<RestMsg<String>>(rm, headers, HttpStatus.OK);
}

From source file:org.openmrs.module.conceptmanagementapps.api.impl.ConceptManagementAppsServiceImpl.java

private void setMapAndSaveConcept(MultipartFile spreadsheetFile) {
    ConceptService cs = Context.getConceptService();
    ICsvMapReader mapReader = null;/*  w w  w  .ja  v a 2s . c  o  m*/
    try {

        mapReader = new CsvMapReader(new InputStreamReader(spreadsheetFile.getInputStream()),
                CsvPreference.STANDARD_PREFERENCE);

        final String[] header = mapReader.getHeader(true);
        final CellProcessor[] processors = getSpreadsheetProcessors();

        for (Map<String, Object> mapList = mapReader.read(header,
                processors); mapList != null; mapList = mapReader.read(header, processors)) {

            ConceptMap conceptMap = new ConceptMap();
            Collection<ConceptMap> conceptMappings;

            ConceptReferenceTerm refTerm = cs.getConceptReferenceTermByCode((String) mapList.get("source code"),
                    cs.getConceptSourceByName((String) mapList.get("source name")));

            conceptMap.setConceptReferenceTerm(refTerm);

            conceptMap.setConceptMapType(cs.getConceptMapTypeByName((String) mapList.get("map type")));

            if (cs.getConcept(((String) mapList.get("concept Id"))) != null) {

                Concept concept = cs.getConcept(((String) mapList.get("concept Id")));

                //see if concept has mappings we need to add to
                if (concept.getConceptMappings() == null) {

                    List<ConceptMap> conceptMappingsList = new ArrayList<ConceptMap>();
                    conceptMappingsList.add(conceptMap);
                    concept.setConceptMappings(conceptMappingsList);

                } else {

                    conceptMappings = concept.getConceptMappings();
                    conceptMappings.add(conceptMap);
                    concept.setConceptMappings(conceptMappings);

                }

                cs.saveConcept(concept);

            }
        }
    }

    catch (APIException e) {
        log.error(e);
        throw new APIException(
                "error on row " + mapReader.getRowNumber() + "," + mapReader.getUntokenizedRow() + e);
    } catch (FileNotFoundException e) {
        log.error(e);
    } catch (IOException e) {
        log.error(e);
    }

    finally {

        if (mapReader != null) {

            try {
                mapReader.close();
            } catch (IOException e) {
                log.error(e);
            }
        }
    }

}

From source file:com.devnexus.ting.web.controller.admin.SponsorController.java

@RequestMapping(value = "/s/admin/{eventKey}/sponsor/{sponsorId}", method = RequestMethod.POST)
public String editSponsor(@PathVariable("sponsorId") Long sponsorId, @RequestParam MultipartFile pictureFile,
        @Valid Sponsor sponsorForm, BindingResult result, RedirectAttributes redirectAttributes,
        HttpServletRequest request) {// w  w  w .  ja  va2s. c om

    if (request.getParameter("cancel") != null) {
        return "redirect:/s/admin/{eventKey}/sponsors";
    }

    if (result.hasErrors()) {
        return "/admin/add-sponsor";
    }

    final Sponsor sponsorFromDb = businessService.getSponsorWithPicture(sponsorId);

    if (request.getParameter("delete") != null) {
        businessService.deleteSponsor(sponsorFromDb);
        redirectAttributes.addFlashAttribute("successMessage", "The sponsor was deleted successfully.");
        return "redirect:/s/admin/{eventKey}/sponsors";
    }

    sponsorFromDb.setLink(sponsorForm.getLink());
    sponsorFromDb.setName(sponsorForm.getName());
    sponsorFromDb.setSortOrder(sponsorForm.getSortOrder());
    sponsorFromDb.setSponsorLevel(sponsorForm.getSponsorLevel());

    if (pictureFile != null && pictureFile.getSize() > 0) {

        final FileData pictureData;
        if (sponsorFromDb.getLogo() == null) {
            pictureData = new FileData();
        } else {
            pictureData = sponsorFromDb.getLogo();
        }

        try {

            pictureData.setFileData(IOUtils.toByteArray(pictureFile.getInputStream()));
            pictureData.setFileSize(pictureFile.getSize());
            pictureData.setFileModified(new Date());
            pictureData.setType(pictureFile.getContentType());
            pictureData.setName(pictureFile.getOriginalFilename());

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        sponsorFromDb.setLogo(pictureData);
    }

    businessService.saveSponsor(sponsorFromDb);

    redirectAttributes.addFlashAttribute("successMessage",
            String.format("The sponsor '%s' was edited successfully.", sponsorFromDb.getName()));

    return "redirect:/s/admin/{eventKey}/sponsors";
}

From source file:net.duckling.ddl.web.api.rest.FileEditController.java

@RequestMapping(value = "/fileShared", method = RequestMethod.POST)
public void fileShared(@RequestParam(value = "path", required = false) String path,
        @RequestParam("file") MultipartFile file,
        @RequestParam(value = "ifExisted", required = false) String ifExisted, HttpServletRequest request,
        HttpServletResponse response) throws IOException {
    String uid = getCurrentUid(request);
    int tid = getCurrentTid();
    path = StringUtils.defaultIfBlank(path, PathName.DELIMITER);

    LOG.info("file shared start... {uid:" + uid + ",tid:" + tid + ",path:" + path + ",fileName:"
            + file.getOriginalFilename() + ",ifExisted:" + ifExisted + "}");

    Resource parent = folderPathService.getResourceByPath(tid, path);
    if (parent == null) {
        LOG.error("path not found. {tid:" + tid + ", path:" + path + "}");
        writeError(ErrorMsg.NOT_FOUND, response);
        return;//from  w  w w .  ja va2  s.  c o m
    }

    List<Resource> list = resourceService.getResourceByTitle(tid, parent.getRid(), LynxConstants.TYPE_FILE,
            file.getOriginalFilename());
    if (list.size() > 0 && !IF_EXISTED_UPDATE.equals(ifExisted)) {
        LOG.error("file existed. {ifExisted:" + ifExisted + ",fileName:" + file.getOriginalFilename() + "}");
        writeError(ErrorMsg.EXISTED, response);
        return;
    }

    FileVersion fv = null;
    try {
        fv = resourceOperateService.upload(uid, getCurrentTid(), parent.getRid(), file.getOriginalFilename(),
                file.getSize(), file.getInputStream());
    } catch (NoEnoughSpaceException e) {
        LOG.error("no enough space. {tid:" + tid + ",size:" + file.getSize() + ",fileName:"
                + file.getOriginalFilename() + "}");
        writeError(ErrorMsg.NO_ENOUGH_SPACE, response);
        return;
    }

    ShareResource sr = shareResourceService.get(fv.getRid());
    if (sr == null) {
        sr = createShareResource(fv.getRid(), uid);
    } else {
        sr.setLastEditor(uid);
        sr.setLastEditTime(new Date());
        shareResourceService.update(sr);
    }
    sr.setTitle(fv.getTitle());
    sr.setShareUrl(sr.generateShareUrl(urlGenerator));

    LOG.info("file uploaded and shared successfully. {tid:" + tid + ",path:" + path + ",title:" + fv.getTitle()
            + "}");
    JsonUtil.write(response, VoUtil.getShareResourceVo(sr));
}