Java Examples for org.springframework.web.multipart.MultipartFile

The following java examples will help you to understand the usage of org.springframework.web.multipart.MultipartFile. These source code samples are taken from different open source projects.

Example 1
Project: Katari-master  File: EmptyAwareMultipartFileEditor.java View source code
/** Sets the value of this editor from the uploaded file.
   *
   * @param value The uploaded file. It is ignored for everything that is not a
   * MultipartFile, even null.
   */
public void setValue(final Object value) {
    if (value instanceof MultipartFile) {
        MultipartFile multipartFile = (MultipartFile) value;
        if (multipartFile.getOriginalFilename().equals("")) {
            // The user did not select a file.
            super.setValue(null);
        } else {
            super.setValue(value);
        }
    }
}
Example 2
Project: geode-master  File: ConvertUtils.java View source code
/**
   * Converts the array of MultipartFiles into a 2-dimensional byte array containing content from
   * each MultipartFile. The 2-dimensional byte array format is used by Gfsh and the GemFire Manager
   * to transmit file data.
   * <p/>
   * 
   * @param files an array of Spring MultipartFile objects to convert into the 2-dimensional byte
   *        array format.
   * @return a 2-dimensional byte array containing the content of each MultipartFile.
   * @throws IOException if an I/O error occurs reading the contents of a MultipartFile.
   * @see #convert(org.springframework.core.io.Resource...)
   * @see org.springframework.web.multipart.MultipartFile
   */
public static byte[][] convert(final MultipartFile... files) throws IOException {
    if (files != null) {
        final List<Resource> resources = new ArrayList<Resource>(files.length);
        for (final MultipartFile file : files) {
            resources.add(new MultipartFileResourceAdapter(file));
        }
        return convert(resources.toArray(new Resource[resources.size()]));
    }
    return new byte[0][];
}
Example 3
Project: cmop-master  File: ImportController.java View source code
/**
	 * 导入
	 * 
	 * @return
	 * @throws IOException
	 */
@RequestMapping(value = "/save", method = RequestMethod.POST)
public String save(@RequestParam MultipartFile file, RedirectAttributes redirectAttributes) throws IOException {
    boolean result = comm.importService.save(file.getInputStream());
    if (result) {
        redirectAttributes.addFlashAttribute("saveMessage", "基础数�导入�功�");
    } else {
        redirectAttributes.addFlashAttribute("message", "基础数�导入失败,请检查Excel文件中数�项格�是�正确� ");
    }
    return "redirect:/basicdata/import";
}
Example 4
Project: EDU_SYZT-master  File: FileUploadController.java View source code
@RequestMapping(value = "/upload", method = RequestMethod.POST)
@ResponseBody
public String handleFileUpload(@RequestParam("name") String name, @RequestParam("file") MultipartFile file) {
    if (!file.isEmpty()) {
        try {
            byte[] bytes = file.getBytes();
            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(name)));
            stream.write(bytes);
            stream.close();
            return "You successfully uploaded " + name + "!";
        } catch (Exception e) {
            return "You failed to upload " + name + " => " + e.getMessage();
        }
    } else {
        return "You failed to upload " + name + " because the file was empty.";
    }
}
Example 5
Project: spring-framework-issues-master  File: FileUploadController.java View source code
@RequestMapping(method = RequestMethod.POST)
public void processUpload(@RequestParam MultipartFile file, HttpServletRequest request, Model model) throws IOException {
    String message = "File '" + file.getOriginalFilename() + "' uploaded successfully";
    // prepare model for rendering success message in this request
    model.addAttribute("message", new Message(MessageType.success, message));
    model.addAttribute("ajaxRequest", AjaxUtils.isAjaxUploadRequest(request));
}
Example 6
Project: spring-guides-master  File: FileUploadController.java View source code
@RequestMapping(value = "/upload", method = RequestMethod.POST)
@ResponseBody
public String handleFileUpload(@RequestParam("name") String name, @RequestParam("file") MultipartFile file) {
    if (!file.isEmpty()) {
        try {
            try (BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(name)))) {
                stream.write(file.getBytes());
            }
            return "You successfully uploaded " + name + "!";
        } catch (IOException e) {
            return "You failed to upload " + name + " => " + e.getMessage();
        }
    } else {
        return "You failed to upload " + name + " because the file was empty.";
    }
}
Example 7
Project: spring-mvc-exts-master  File: JxlsController.java View source code
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public String handleFormUpload(@RequestParam("file") MultipartFile file, Model model) throws InvalidFormatException, IOException, SAXException {
    Department department = new Department();
    model.addAttribute(department);
    jxlsFileReader.read(uploadFileTemplate, file, model);
    System.out.println(department);
    System.out.println(department.getChief());
    System.out.println(department.getStaff());
    return "redirect:/";
}
Example 8
Project: yy-utils-master  File: AbstractUploader.java View source code
public UploadResult upload(MultipartFile file, String path, String rename, AbstractUploadFilter filter) throws UploadException, IOException {
    if (file == null) {
        throw new UploadException("MultipartFile unavailable.");
    }
    String originalName = file.getOriginalFilename();
    if (Strings.isNullOrEmpty(originalName)) {
        throw new UploadException("Empty name of uploaded file.");
    }
    if (filter != null) {
        filter.filter(originalName);
    }
    String resultName = originalName;
    if (!Strings.isNullOrEmpty(rename)) {
        int start = originalName.lastIndexOf(".");
        start = start == -1 ? 0 : start;
        String suffix = originalName.substring(start, originalName.length());
        suffix = suffix.startsWith(".") ? suffix : "." + suffix;
        resultName = rename + suffix;
    }
    if (!path.endsWith("/")) {
        path = path + "/";
    }
    return putObject(file, path, originalName, resultName);
}
Example 9
Project: iBeaconServer-master  File: BeaconController.java View source code
/**
     * Create a new beacon in region.
     * <p>
     * Beacon creation request JSON:
     * <pre>
     * {
     *   "uuid":"12345678-1234-1234-1234-123456789012",
     *   "major":"1",
     *   "minor":"2",
     *   "xCoordinate":"150"
     *   "yCoordinate":"120"
     *   "designated":"true"
     *   "displayName":"Room 237"
     *   "description":"Beacon description"
     * }
     * </pre>
     *
     * @param username
     *         The username of the owner of the project
     * @param projectId
     *         The ID of the project to create the beacon in
     * @param regionId
     *         The ID of the region
     * @param beacon
     *         The beacon parsed from the JSON object
     * @param locationInfoText
     *         The [optional] location info text as a {@link MultipartFile}.
     * @param builder
     *         The URI builder for post-creation redirect
     *
     * @return The created beacon
     */
@RequestMapping(method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Beacon> createBeacon(@PathVariable String username, @PathVariable Long projectId, @PathVariable Long regionId, @RequestPart(value = "beacon") Beacon beacon, @RequestPart(value = "info", required = false) MultipartFile locationInfoText, UriComponentsBuilder builder) throws TextSaveException {
    Beacon savedBeacon = beaconService.saveNewBeacon(username, projectId, regionId, beacon, locationInfoText);
    GlobalSettings.log("Saved beacon with UUID = \'" + savedBeacon.getUuid() + "\' major = \'" + savedBeacon.getMajor() + "\' minor = \'" + savedBeacon.getMinor() + "\' in project with ID = \'" + projectId + "\'");
    addLinks(username, projectId, regionId, savedBeacon);
    return buildCreateResponse(username, builder, savedBeacon);
}
Example 10
Project: aranea-master  File: EditImageController.java View source code
@Override
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object object, BindException errors) throws Exception {
    Image image = (Image) object;
    // set the photographer to null if externalsource is set.
    if (request.getParameter("externalsource") != null && request.getParameter("externalsource").length() > 0) {
        image.setPhotographer(null);
    }
    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
    MultipartFile file = multipartRequest.getFile("file_");
    if (file != null && file.getSize() != 0) {
        image = storeImageService.changeImage(file, image);
    }
    return super.onSubmit(request, response, image, errors);
}
Example 11
Project: bugCatcher-master  File: FileSystemStorageService.java View source code
@Override
public void store(MultipartFile file) {
    try {
        //            if (file.isEmpty()) {
        //                throw new StorageException("Failed to store empty file " + file.getOriginalFilename());
        //            }
        Files.copy(file.getInputStream(), this.rootLocation.resolve(file.getOriginalFilename()));
    } catch (IOException e) {
        throw new StorageException("Failed to store file " + file.getOriginalFilename(), e);
    }
}
Example 12
Project: deposit-forms-master  File: DepositFileEditor.java View source code
public void setValue(Object value) {
    if (value instanceof MultipartFile) {
        MultipartFile multipartFile = (MultipartFile) value;
        if (multipartFile.getOriginalFilename().length() == 0) {
            super.setValue(null);
            return;
        }
        try {
            File temp = File.createTempFile("temp", ".tmp");
            multipartFile.transferTo(temp);
            DepositFile depositFile = new DepositFile();
            depositFile.setFile(temp);
            depositFile.setFilename(multipartFile.getOriginalFilename());
            depositFile.setContentType(multipartFile.getContentType());
            depositFile.setSize(multipartFile.getSize());
            super.setValue(depositFile);
        } catch (IOException e) {
            throw new IllegalArgumentException(e);
        }
    } else if (value instanceof DepositFile) {
        super.setValue(value);
    } else {
        super.setValue(null);
    }
}
Example 13
Project: dionysus-master  File: FileUploadController.java View source code
@RequestMapping(value = "/upload", method = RequestMethod.POST)
@ResponseBody
public UploadResult handleFileUpload(@RequestParam("file") MultipartFile file) throws StorageException {
    if (!file.isEmpty()) {
        try {
            String id = storage.save(file.getBytes());
            String link = storage.url(id);
            return new UploadResult(link);
        } catch (IOException e) {
            throw new StorageException(e.getMessage());
        }
    }
    return new UploadResult("");
}
Example 14
Project: extdirectspring-master  File: FileUploadController.java View source code
@ExtDirectMethod(value = ExtDirectMethodType.FORM_POST, group = "itest_upload", event = "test", entryClass = String.class, synchronizeOnSession = true)
@RequestMapping(value = "/test", method = RequestMethod.POST)
public void uploadTest(HttpServletRequest request, @RequestParam("fileUpload") MultipartFile file, final HttpServletResponse response, @Valid User user, BindingResult result) throws IOException {
    ExtDirectResponseBuilder builder = new ExtDirectResponseBuilder(request, response);
    if (file != null && !file.isEmpty()) {
        builder.addResultProperty("fileContents", new String(file.getBytes()));
        builder.addResultProperty("fileName", file.getOriginalFilename());
    }
    builder.addErrors(result);
    builder.addResultProperty("name", user.getName());
    builder.addResultProperty("firstName", user.getFirstName());
    builder.addResultProperty("age", user.getAge());
    builder.addResultProperty("email", user.getEmail());
    builder.successful();
    builder.buildAndWrite();
}
Example 15
Project: FreeEedUI-master  File: FileUploadController.java View source code
@Override
public ModelAndView execute() {
    if (!(request instanceof MultipartHttpServletRequest)) {
        valueStack.put("status", "error");
        return null;
    }
    log.debug("Uploading file...");
    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
    MultipartFile file = multipartRequest.getFile("file");
    String dest = caseFileService.uploadFile(file);
    if (dest != null) {
        valueStack.put("fileName", dest.replace("\\", "\\\\"));
        valueStack.put("fileNameShort", dest.lastIndexOf(File.separator) == -1 ? dest : dest.substring(dest.lastIndexOf(File.separator) + 1));
        valueStack.put("status", "success");
    } else {
        valueStack.put("status", "error");
    }
    return new ModelAndView(WebConstants.UPLOAD_FILE);
}
Example 16
Project: gocd-master  File: FakeArtifactPublisherServlet.java View source code
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
    MultipartHttpServletRequest httpServletRequest = multipartResolver.resolveMultipart(request);
    Map<String, MultipartFile> map = httpServletRequest.getFileMap();
    MultipartFile multipartFile = map.values().iterator().next();
    receivedFiles.add(multipartFile.getOriginalFilename());
}
Example 17
Project: hishare-master  File: UploadParcelController.java View source code
@RequestMapping(value = "/file", method = RequestMethod.POST)
public ModelAndView handleFormUpload(@RequestParam("username") String username, @RequestParam("authenticationId") String authenticationId, @RequestParam("parcelName") String parcelName, @RequestParam("daysToLive") Integer daysToLive, @RequestParam("file") MultipartFile file) throws IOException {
    ModelAndView mav;
    byte[] payload = null;
    if (!file.isEmpty()) {
        payload = file.getBytes();
    }
    mav = new ModelAndView("outputString");
    String[] accessInfo = uploadParcel.uploadParcel(username, authenticationId, parcelName, daysToLive, payload);
    String output = accessInfo[0] + ":" + accessInfo[1];
    mav.addObject("string", output);
    return mav;
}
Example 18
Project: jblog-master  File: UploadController.java View source code
/*@RequestMapping("/upload_page")
	public String uploadPage(){
		
		return "/admin/upload";
	}*/
@ResponseBody
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public String uploadFile(MultipartHttpServletRequest request) {
    try {
        Iterator<String> itr = request.getFileNames();
        while (itr.hasNext()) {
            String uploadedFile = itr.next();
            MultipartFile file = request.getFile(uploadedFile);
            String mimeType = file.getContentType();
            String filename = file.getOriginalFilename();
            byte[] bytes = file.getBytes();
            InputStream input = file.getInputStream();
            File source = new File("C://" + filename);
            file.transferTo(source);
        //                FileUpload newFile = new FileUpload(filename, bytes, mimeType);
        }
    } catch (Exception e) {
        e.printStackTrace();
        return "{error}";
    }
    return "{ok}";
}
Example 19
Project: jdyna-master  File: ValoreDTOPropertyEditor.java View source code
@Override
public void setValue(Object arg0) {
    super.setValue(arg0);
    if (arg0 instanceof MultipartFile) {
        internalPropertyEditor.setValue(arg0);
        setValue(internalPropertyEditor.getValue());
    } else {
        ValoreDTO valoreDTO = (ValoreDTO) arg0;
        internalPropertyEditor.setValue(valoreDTO == null ? null : valoreDTO.getObject());
    }
}
Example 20
Project: jogetworkflow-master  File: ResourceBundleMessageWebController.java View source code
@RequestMapping(value = "/settings/resource/message/import/submit", method = RequestMethod.POST)
public String POFileUpload(ModelMap map) throws Exception {
    String systemLocale = "";
    if (setupManager.getSettingByProperty("systemLocale") != null) {
        systemLocale = setupManager.getSettingByProperty("systemLocale").getValue();
    }
    if (systemLocale.equalsIgnoreCase("")) {
        systemLocale = "en_US";
    }
    try {
        MultipartFile multiPartfile = FileStore.getFile("localeFile");
        resourceBundleUtil.POFileImport(multiPartfile, systemLocale);
    } catch (IOException e) {
    }
    map.addAttribute("localeList", getSortedLocalList());
    return "message/messageList";
}
Example 21
Project: lemon-master  File: CdnUtils.java View source code
public static String copyMultipartFileToFile(String baseDir, MultipartFile multipartFile, String spaceName, String targetFileName) throws Exception {
    if (targetFileName == null) {
        return copyMultipartFileToFile(baseDir, multipartFile, spaceName);
    }
    if (targetFileName.indexOf("../") != -1) {
        logger.info("invalid : {}", targetFileName);
        throw new IllegalStateException("invalid : " + targetFileName);
    }
    File file = findTargetFile(baseDir, spaceName, targetFileName);
    multipartFile.transferTo(file);
    return targetFileName;
}
Example 22
Project: mateo-master  File: FileUploadHandler.java View source code
public void processFile(String username) throws IOException {
    String name = file.getName();
    log.debug("nombre archivo{}", name);
    List<MultipartFile> files = new ArrayList<>();
    files.add(file);
    files.add(file);
    List<String> fileNames = new ArrayList<String>();
    if (null != files && files.size() > 0) {
        for (MultipartFile multipartFile : files) {
            String fileName = multipartFile.getOriginalFilename();
            fileNames.add(fileName);
            String uploadDir = "/home/facturas/" + username + "/" + multipartFile.getOriginalFilename();
            File dirPath = new File(uploadDir);
            if (!dirPath.exists()) {
                dirPath.mkdirs();
            }
            multipartFile.transferTo(new File("/home/facturas/" + username + "/" + multipartFile.getOriginalFilename()));
            if (multipartFile.getOriginalFilename().contains(".pdf")) {
            //                    detalle.setPathPDF("/home/facturas/" + request.getRemoteUser() + "/" + multipartFile.getOriginalFilename());
            //                    detalle.setNombrePDF(multipartFile.getOriginalFilename());
            }
            if (multipartFile.getOriginalFilename().contains(".xml")) {
            //                    detalle.setPathXMl("/home/facturas/" + request.getRemoteUser() + "/" + multipartFile.getOriginalFilename());
            //                    detalle.setNombreXMl(multipartFile.getOriginalFilename());
            }
        }
    }
}
Example 23
Project: online-whatif-master  File: ZipFileUploadController.java View source code
/**
   * Save. TODO Make this a real automated test.
   * 
   * @param uploadForm
   *          the upload form
   * @param map
   *          the map
   * @return the string
   * @throws ShapeFile2PostGISCreationException
   *           the shape file2 post gis creation exception
   * @throws ZipFileExtractionException
   *           the zip file extraction exception
   */
@RequestMapping(value = "/saveFile", method = RequestMethod.POST, produces = "text/plain")
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public String save(@ModelAttribute("uploadForm") UploadForm uploadForm, Model map) throws ShapeFile2PostGISCreationException, ZipFileExtractionException {
    LOGGER.info("Saving the following file:");
    MultipartFile multipartFile = uploadForm.getFile();
    String filename = multipartFile.getOriginalFilename();
    LOGGER.info("Filename = {}", filename);
    File resultFile = fileToPostgisExporter.getZipFile(multipartFile);
    LOGGER.info("AbsolutePath = {}", resultFile.getAbsolutePath());
    return resultFile.getAbsolutePath();
}
Example 24
Project: opentides3-master  File: ImageValidator.java View source code
@Override
public void validate(Object obj, Errors errors) {
    AjaxUpload ajaxUpload = (AjaxUpload) obj;
    MultipartFile attachment = ajaxUpload.getAttachment();
    ValidationUtils.rejectIfEmpty(errors, "attachment", "photo.image-required");
    if (attachment != null && !attachment.isEmpty()) {
        String contentType = attachment.getContentType().substring(0, 6);
        if (!"image/".equals(contentType)) {
            errors.rejectValue("attachment", "photo.invalid-file-type", "Invalid file. Profile Image must be in PNG, JPEG, GIF or BMP format.");
        } else if (attachment.getSize() > 1024 * 1024 * 10) {
            errors.rejectValue("attachment", "photo.invalid-file-size", "Invalid file. Maximum file size is 10 Megabytes");
        }
    }
}
Example 25
Project: service-registration-and-discovery-master  File: Application.java View source code
@RequestMapping(method = { RequestMethod.POST, RequestMethod.PUT })
ResponseEntity<?> set(String userId, @RequestParam MultipartFile multipartFile, UriComponentsBuilder uriBuilder) throws IOException {
    try (InputStream inputStream = multipartFile.getInputStream()) {
        this.gridFsTemplate.store(inputStream, userId);
    }
    URI uri = uriBuilder.path("/{userId}/photo").buildAndExpand(userId).toUri();
    HttpHeaders headers = new HttpHeaders();
    headers.setLocation(uri);
    return new ResponseEntity<>(headers, HttpStatus.CREATED);
}
Example 26
Project: shopb2b-master  File: FileUploadService.java View source code
public void build(ProductImage productImage) {
    // 得到图片文件
    MultipartFile localMultipartFile = productImage.getFile();
    if ((localMultipartFile != null) && (!localMultipartFile.isEmpty())) {
        String str2 = UUID.randomUUID().toString();
        String sourceName = str2 + "-source." + FilenameUtils.getExtension(localMultipartFile.getOriginalFilename());
        String largeName = str2 + "-large." + jpgImage;
        String str = System.getProperty("java.io.tmpdir");
        File localFile = new File(str + "/upload_" + UUID.randomUUID() + ".tmp");
        if (!localFile.getParentFile().exists())
            localFile.getParentFile().mkdirs();
        // Transfer the received file to the given destination file.
        int width = 100;
        int height = 200;
        File localFile2 = new File(str + "/upload_" + UUID.randomUUID() + "." + jpgImage);
        try {
            localMultipartFile.transferTo(localFile);
            ImageUtils.zoom(localFile, localFile2, width, height);
            File oriFile = new File(this.servletContext.getRealPath(sourceName));
            FileUtils.moveFile(localFile, oriFile);
            File localFileChange = new File(this.servletContext.getRealPath(largeName));
            FileUtils.moveFile(localFile2, localFileChange);
        } catch (Exception localException1) {
            localException1.printStackTrace();
        } finally {
            // 原始图�
            FileUtils.deleteQuietly(localFile);
            FileUtils.deleteQuietly(localFile2);
        }
    }
}
Example 27
Project: spring-app-store-master  File: ShopService.java View source code
public boolean addApp(String name, MultipartFile file, String path, Date date, String description) throws IOException, ZipException, ObjectNotFoundException {
    if (!storageUtils.storeFile(file, path, date)) {
        logger.error("File storage failed.");
        return false;
    }
    Application application = storageUtils.extractFileContent(name, file, path);
    if (application == null) {
        storageUtils.cleanUpFiles(file, path);
        logger.error("File contains wrong content. File removed from server.");
        return false;
    }
    application.setTimeUploaded(date);
    application.setDescription(description);
    shopDao.save(application);
    return true;
}
Example 28
Project: spring-framework-2.5.x-master  File: WebDataBinder.java View source code
/**
	 * Bind the multipart files contained in the given request, if any
	 * (in case of a multipart request).
	 * <p>Multipart files will only be added to the property values if they
	 * are not empty or if we're configured to bind empty multipart files too.
	 * @param multipartFiles Map of field name String to MultipartFile object
	 * @param mpvs the property values to be bound (can be modified)
	 * @see org.springframework.web.multipart.MultipartFile
	 * @see #setBindEmptyMultipartFiles
	 */
protected void bindMultipartFiles(Map multipartFiles, MutablePropertyValues mpvs) {
    for (Iterator it = multipartFiles.entrySet().iterator(); it.hasNext(); ) {
        Map.Entry entry = (Map.Entry) it.next();
        String key = (String) entry.getKey();
        MultipartFile value = (MultipartFile) entry.getValue();
        if (isBindEmptyMultipartFiles() || !value.isEmpty()) {
            mpvs.addPropertyValue(key, value);
        }
    }
}
Example 29
Project: spring-framework-master  File: WebDataBinder.java View source code
/**
	 * Bind all multipart files contained in the given request, if any
	 * (in case of a multipart request).
	 * <p>Multipart files will only be added to the property values if they
	 * are not empty or if we're configured to bind empty multipart files too.
	 * @param multipartFiles Map of field name String to MultipartFile object
	 * @param mpvs the property values to be bound (can be modified)
	 * @see org.springframework.web.multipart.MultipartFile
	 * @see #setBindEmptyMultipartFiles
	 */
protected void bindMultipart(Map<String, List<MultipartFile>> multipartFiles, MutablePropertyValues mpvs) {
    for (Map.Entry<String, List<MultipartFile>> entry : multipartFiles.entrySet()) {
        String key = entry.getKey();
        List<MultipartFile> values = entry.getValue();
        if (values.size() == 1) {
            MultipartFile value = values.get(0);
            if (isBindEmptyMultipartFiles() || !value.isEmpty()) {
                mpvs.add(key, value);
            }
        } else {
            mpvs.add(key, values);
        }
    }
}
Example 30
Project: spring-project-template-master  File: UserService.java View source code
@Transactional
public void updateProfile(long userId, MultipartFile file) throws Exception {
    MediaType mediaType = MediaType.parseMediaType(file.getContentType());
    File f = new File(path + File.separator + System.currentTimeMillis() + "." + mediaType.getSubtype());
    file.transferTo(f);
    User user = userRepository.findOne(userId);
    user.setImagePath(f.getAbsolutePath());
    userRepository.saveAndFlush(user);
}
Example 31
Project: spring-rest-client-master  File: UploadApiTest.java View source code
@Test
public void testTwo2() throws IOException {
    MockMultipartFile file1 = new MockMultipartFile("myimage1.image", "/originial/name1", null, "Hello test one1111".getBytes("UTF-8"));
    MockMultipartFile file2 = new MockMultipartFile("myimage2.image", "/originial/name2", null, "Hello test one22222".getBytes("UTF-8"));
    uploadApi.images2("bingoohuang.txt", Lists.<MultipartFile>newArrayList(file1, file2));
}
Example 32
Project: weplantaforest-master  File: ImageHelper.java View source code
public String storeImage(MultipartFile file, String folder, String imageName, boolean overwriteExistingImage) throws IOException {
    if (!folderExists(folder)) {
        createNewFolder(folder);
    }
    if (!overwriteExistingImage) {
        if (imageNameExists(folder, imageName)) {
            imageName = createNonExistingImageName(folder, imageName);
        }
    }
    byte[] bytes = null;
    bytes = file.getBytes();
    File fileToSave = new File(folder, imageName);
    FileOutputStream fileOutPutStreamfromFileToSave = null;
    fileOutPutStreamfromFileToSave = new FileOutputStream(fileToSave);
    BufferedOutputStream stream = new BufferedOutputStream(fileOutPutStreamfromFileToSave);
    stream.write(bytes);
    stream.close();
    fileOutPutStreamfromFileToSave.close();
    return imageName;
}
Example 33
Project: Activiti-master  File: TaskAttachmentCollectionResource.java View source code
protected AttachmentResponse createBinaryAttachment(MultipartHttpServletRequest request, Task task, HttpServletResponse response) {
    String name = null;
    String description = null;
    String type = null;
    Map<String, String[]> paramMap = request.getParameterMap();
    for (String parameterName : paramMap.keySet()) {
        if (paramMap.get(parameterName).length > 0) {
            if (parameterName.equalsIgnoreCase("name")) {
                name = paramMap.get(parameterName)[0];
            } else if (parameterName.equalsIgnoreCase("description")) {
                description = paramMap.get(parameterName)[0];
            } else if (parameterName.equalsIgnoreCase("type")) {
                type = paramMap.get(parameterName)[0];
            }
        }
    }
    if (name == null) {
        throw new ActivitiIllegalArgumentException("Attachment name is required.");
    }
    if (request.getFileMap().size() == 0) {
        throw new ActivitiIllegalArgumentException("Attachment content is required.");
    }
    MultipartFile file = request.getFileMap().values().iterator().next();
    if (file == null) {
        throw new ActivitiIllegalArgumentException("Attachment content is required.");
    }
    try {
        Attachment createdAttachment = taskService.createAttachment(type, task.getId(), task.getProcessInstanceId(), name, description, file.getInputStream());
        response.setStatus(HttpStatus.CREATED.value());
        return restResponseFactory.createAttachmentResponse(createdAttachment);
    } catch (Exception e) {
        throw new ActivitiException("Error creating attachment response", e);
    }
}
Example 34
Project: albert-master  File: UploadFileUtils.java View source code
/**
	 * 文件é‡?命å??
	 * @param file
	 * @return
	 */
public static String rename(MultipartFile file) {
    //获å?–原始文件å??  
    String fileName = file.getOriginalFilename();
    //新文件å??称,ä¸?设置时默认为原文件å??
    String newFileName = new Date().getTime() + (new Random().nextInt(9999 - 1000 + 1) + 1000) + fileName.substring(fileName.lastIndexOf('.'));
    return newFileName;
}
Example 35
Project: android-translator-helper-master  File: FileUploadController.java View source code
@//
RequestMapping(//
value = "/upload", //
method = RequestMethod.POST, //
consumes = { MediaType.MULTIPART_FORM_DATA_VALUE }, produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public SourceStringsResource upload(@RequestParam("sourceLang") String sourceLang, @RequestParam("targetLangs") String targetLangs, @RequestParam("sourceFile") MultipartFile sourceFile, @RequestParam("translator") String translator) {
    if (!sourceFile.isEmpty()) {
        try {
            List<SourceItem> strings = translationService.parseSourceFile(sourceFile.getBytes());
            Map<String, TranslationFile> files = translationService.translate(strings, sourceLang, Arrays.asList(targetLangs.split(", ")), translator);
            return new SourceStringsResource(HttpStatus.ACCEPTED.value(), strings, files);
        } catch (IOException e) {
            LOG.error("Failed to parse uploaded file", e);
            throw new SourceStringsParserException(Arrays.asList("Server could not read your source file. Please review your file and try again"));
        }
    } else {
        LOG.error("Uploaded source file is empty");
        throw new SourceStringsParserException(Arrays.asList("Uploaded source file is empty! Please, try again with a valid file"));
    }
}
Example 36
Project: balerocms-enterprise-master  File: FileUploadController.java View source code
/**
     * Uploading images asyncronic method for summernote
     * @author Anibal Gomez <anibalgomez@icloud.com>
     * References:
     * https://spring.io/guides/gs/uploading-files/
     * http://stackoverflow.com/questions/21628222/summernote-image-upload
     * https://developer.mozilla.org/en-US/docs/Web/API/FormData/append
     * https://github.com/CollectionFS/Meteor-CollectionFS/issues/489
     * http://stackoverflow.com/questions/14089146/file-loading-by-getclass-getresource
     * @param file
     * @return
     */
@Secured({ "ROLE_ADMIN", "ROLE_USER" })
@RequestMapping(value = "/upload", method = RequestMethod.POST)
@ResponseBody
public HttpStatus handleFileUpload(@RequestParam("file") MultipartFile file) {
    log.debug("POST /upload {}");
    String filePath = FileUploadController.class.getResource("/static/images/uploads/").getPath() + file.getOriginalFilename();
    if (!file.isEmpty()) {
        try {
            byte[] bytes = file.getBytes();
            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(filePath)));
            stream.write(bytes);
            stream.close();
            log.debug("Creating file: " + filePath);
            log.debug("You successfully uploaded " + file.getOriginalFilename() + "!");
            return HttpStatus.OK;
        } catch (Exception e) {
            log.debug("You failed to upload " + file.getOriginalFilename() + " => " + e.getMessage());
            return HttpStatus.FORBIDDEN;
        }
    } else {
        log.debug("You failed to upload " + file.getOriginalFilename() + " because the file was empty.");
        return HttpStatus.FORBIDDEN;
    }
}
Example 37
Project: categolj2-backend-master  File: FileHelper.java View source code
UploadFile multipartFileToUploadFile(MultipartFile multipartFile) {
    UploadFile uploadFile = new UploadFile();
    uploadFile.setFileName(multipartFile.getOriginalFilename());
    try {
        uploadFile.setFileContent(multipartFile.getBytes());
    } catch (IOException e) {
        throw new SystemException("upload failed", e);
    }
    return uploadFile;
}
Example 38
Project: corespring-master  File: HomeController.java View source code
@RequestMapping(value = "/executarRegistro", method = RequestMethod.POST)
public String executarRegistro(@Valid Usuario usuario, BindingResult bindingResult, HttpSession session, @RequestParam(value = "avatar", required = false) MultipartFile avatar) {
    if (bindingResult.hasErrors()) {
        Map<String, Object> model = new HashMap<String, Object>();
        model.put("usuario", usuario);
        return registro(model);
    }
    getDaoUsuario().persist(usuario);
    if (!avatar.isEmpty()) {
        processarAvatar(usuario, avatar);
    }
    session.setAttribute("usuario", usuario);
    return "redirect:/";
}
Example 39
Project: disconf-master  File: ConfigUpdateController.java View source code
/**
     * �置文件的更新
     *
     * @param configId
     * @param file
     *
     * @return
     */
@ResponseBody
@RequestMapping(value = "/file/{configId}", method = RequestMethod.POST)
public JsonObjectBase updateFile(@PathVariable long configId, @RequestParam("myfilerar") MultipartFile file) {
    //
    // 校验
    //
    int fileSize = 1024 * 1024 * 4;
    String[] allowExtName = { ".properties", ".xml" };
    fileUploadValidator.validateFile(file, fileSize, allowExtName);
    // 业务校验
    configValidator.validateUpdateFile(configId, file.getOriginalFilename());
    //
    // æ›´æ–°
    //
    String emailNotification = "";
    try {
        String str = new String(file.getBytes(), "UTF-8");
        LOG.info("receive file: " + str);
        emailNotification = configMgr.updateItemValue(configId, str);
        LOG.info("update " + configId + " ok");
    } catch (Exception e) {
        LOG.error(e.toString());
        throw new FileUploadException("upload file error", e);
    }
    //
    // 通知ZK
    //
    configMgr.notifyZookeeper(configId);
    return buildSuccess(emailNotification);
}
Example 40
Project: eswaraj-master  File: LocationController.java View source code
@RequestMapping(value = "/location/upload/{locationId}", method = RequestMethod.POST)
@ResponseBody
public String handleFileUpload(@RequestParam("name") String name, @RequestParam("file") MultipartFile file, @PathVariable Long locationId) {
    if (!file.isEmpty()) {
        try {
            customService.processLocationBoundaryFile(locationId, file.getInputStream());
            return "You successfully uploaded " + name + " into " + name + "-uploaded !";
        } catch (Exception e) {
            return "You failed to upload " + name + " => " + e.getMessage();
        }
    } else {
        return "You failed to upload " + name + " because the file was empty.";
    }
}
Example 41
Project: FlowerPaper-master  File: DocumentController.java View source code
@RequestMapping(value = "/save", method = RequestMethod.POST)
public String save(@Valid @ModelAttribute("document") Document document, BindingResult result, @RequestParam("file") MultipartFile file) {
    if (result.hasErrors()) {
        return "doc/documents.tiles";
    }
    System.out.println("Name:" + document.getName());
    System.out.println("Desc:" + document.getDescription());
    System.out.println("File:" + file.getName());
    System.out.println("ContentType:" + file.getContentType());
    try {
        Blob blob = Hibernate.createBlob(file.getInputStream());
        document.setFilename(file.getOriginalFilename());
        document.setContent(blob);
        document.setContentType(file.getContentType());
    } catch (IOException e) {
        e.printStackTrace();
    }
    try {
        documentService.save(document);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return "redirect:/doc/index";
}
Example 42
Project: LearningCommunity-master  File: MultipartFileUtils.java View source code
/**
	 * 存储文件
	 * å°†MultipartFileæ ¼å¼?的文件存储到存储介质上,命å??æ ¼å¼?为MD5Hash(name+UNIX时间戳)
	 * 将存储的�对路径返回
	 * @param multipartFile		待存储的文件
	 * @param path				存储的路径
	 * @return					文件的�对路径
	 */
public static String saveFile(MultipartFile multipartFile, String path) {
    long unixTime = System.currentTimeMillis();
    String name = HashUtils.HashPath(multipartFile.getOriginalFilename() + unixTime);
    String multipartUrl = path + "/" + name;
    File file = null;
    try {
        file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }
        byte[] buffer = multipartFile.getBytes();
        FileOutputStream fStream = new FileOutputStream(multipartUrl);
        fStream.write(buffer);
        fStream.close();
    } catch (IOException e) {
        multipartUrl = "";
        e.printStackTrace();
    }
    return multipartUrl;
}
Example 43
Project: m3s-master  File: MultipleFilesUploadBean.java View source code
/**
	 * 
	 * @return
	 */
public List<MultipartFile> getFiles() {
    List<MultipartFile> list = new ArrayList<MultipartFile>();
    if (file1 != null && !file1.isEmpty())
        list.add(file1);
    if (file2 != null && !file2.isEmpty())
        list.add(file2);
    if (file3 != null && !file3.isEmpty())
        list.add(file3);
    if (file4 != null && !file4.isEmpty())
        list.add(file4);
    if (file5 != null && !file5.isEmpty())
        list.add(file5);
    if (file6 != null && !file6.isEmpty())
        list.add(file6);
    return list;
}
Example 44
Project: OpenConext-teams-master  File: InvitationFormValidatorTest.java View source code
@Test
public void testValidateForCSVInput() throws Exception {
    InvitationForm form = new InvitationForm();
    String mails = "test@example.com,test@example.net,john.doe@example.org";
    MultipartFile mockFile = new MockMultipartFile("mockFile", "test.csv", "text/csv", mails.getBytes("utf-8"));
    form.setCsvFile(mockFile);
    Errors errors = new BeanPropertyBindingResult(form, "invitationForm");
    validator.validate(form, errors);
    assertEquals(0, errors.getErrorCount());
}
Example 45
Project: openmrs-module-webservices.rest-master  File: FormResourceController1_9.java View source code
@RequestMapping(value = "/rest/" + RestConstants.VERSION_1 + "/form/{uuid}/resource/{resourceUuid}/value", method = RequestMethod.POST, headers = { "Content-Type=multipart/form-data" })
@ResponseBody
public Object createResourceValue(@PathVariable("uuid") String formUuid, @PathVariable("resourceUuid") String resourceUuid, @RequestParam("value") MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws Exception {
    //Get the resource
    FormResource resource = formService.getFormResourceByUuid(resourceUuid);
    if (resource == null) {
        throw new IllegalArgumentException("No form resource with uuid " + resourceUuid + " found");
    }
    String clobUuid = clobDatatypeStorageController.create(file, request, response);
    resource.setValueReferenceInternal(clobUuid);
    formService.saveFormResource(resource);
    return new FormResourceResource1_9().asDefaultRep(resource);
}
Example 46
Project: raml-tester-master  File: SpringMockRamlRequest.java View source code
@Override
public Values getFormValues() {
    final Values values = new Values(delegate.getParameterMap());
    if (delegate instanceof MockMultipartHttpServletRequest) {
        for (final Map.Entry<String, List<MultipartFile>> entry : ((MockMultipartHttpServletRequest) delegate).getMultiFileMap().entrySet()) {
            for (int i = 0; i < entry.getValue().size(); i++) {
                values.addValue(entry.getKey(), new FileValue());
            }
        }
    }
    return values;
}
Example 47
Project: spring-android-samples-master  File: FileUploadController.java View source code
/**
	 * Accepts a POST request with multipart/form-data content
	 * @param name the name of the file being uploaded
	 * @param file the binary file
	 * @return response message indicating success or failure
	 */
@RequestMapping(value = "postformdata", method = RequestMethod.POST, headers = "Content-Type=multipart/form-data")
@ResponseBody
public String handleFormUpload(@RequestParam("description") String description, @RequestParam("file") MultipartFile file) {
    if (!file.isEmpty()) {
        byte[] bytes = null;
        try {
            bytes = file.getBytes();
        } catch (IOException e) {
            logger.info("error processing uploaded file", e);
        }
        return "file upload received! Name:[" + description + "] Size:[" + bytes.length + "]";
    } else {
        return "file upload failed!";
    }
}
Example 48
Project: spring-boot-samples-master  File: MainController.java View source code
/**
   * POST /uploadFile -> receive and locally save a file.
   * 
   * @param uploadfile The uploaded file as Multipart file parameter in the 
   * HTTP request. The RequestParam name must be the same of the attribute 
   * "name" in the input tag with type file.
   * 
   * @return An http OK status in case of success, an http 4xx status in case 
   * of errors.
   */
@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<?> uploadFile(@RequestParam("uploadfile") MultipartFile uploadfile) {
    try {
        // Get the filename and build the local file path
        String filename = uploadfile.getOriginalFilename();
        String directory = env.getProperty("netgloo.paths.uploadedFiles");
        String filepath = Paths.get(directory, filename).toString();
        // Save the file locally
        BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(filepath)));
        stream.write(uploadfile.getBytes());
        stream.close();
    } catch (Exception e) {
        System.out.println(e.getMessage());
        return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
    }
    return new ResponseEntity<>(HttpStatus.OK);
}
Example 49
Project: spring-cloud-netflix-master  File: RequestContentDataExtractor.java View source code
private static MultiValueMap<String, Object> extractFromMultipartRequest(MultipartHttpServletRequest request) throws IOException {
    MultiValueMap<String, Object> builder = new LinkedMultiValueMap<>();
    Set<String> queryParams = findQueryParams(request);
    for (Entry<String, String[]> entry : request.getParameterMap().entrySet()) {
        String key = entry.getKey();
        if (!queryParams.contains(key)) {
            for (String value : entry.getValue()) {
                HttpHeaders headers = new HttpHeaders();
                String type = request.getMultipartContentType(key);
                if (type != null) {
                    headers.setContentType(MediaType.valueOf(type));
                }
                builder.add(key, new HttpEntity<>(value, headers));
            }
        }
    }
    for (Entry<String, List<MultipartFile>> parts : request.getMultiFileMap().entrySet()) {
        for (MultipartFile file : parts.getValue()) {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentDispositionFormData(file.getName(), file.getOriginalFilename());
            if (file.getContentType() != null) {
                headers.setContentType(MediaType.valueOf(file.getContentType()));
            }
            HttpEntity entity = new HttpEntity<>(new InputStreamResource(file.getInputStream()), headers);
            builder.add(parts.getKey(), entity);
        }
    }
    return builder;
}
Example 50
Project: spring-integration-master  File: SimpleMultipartFileReader.java View source code
@Override
public Object readMultipartFile(MultipartFile multipartFile) throws IOException {
    if (multipartFile.getContentType() != null && multipartFile.getContentType().startsWith("text")) {
        MediaType contentType = MediaType.parseMediaType(multipartFile.getContentType());
        Charset charset = contentType.getCharset();
        if (charset == null) {
            charset = this.defaultCharset;
        }
        return new String(multipartFile.getBytes(), charset.name());
    } else {
        return multipartFile.getBytes();
    }
}
Example 51
Project: springlab-master  File: SpitterController.java View source code
@RequestMapping(method = RequestMethod.POST)
public String addSpitterFromForm(@Valid Spitter spitter, BindingResult bindingResult, @RequestParam(value = "image", required = false) MultipartFile image) {
    if (bindingResult.hasErrors()) {
        return "spitters/edit";
    }
    spitterService.saveSpitter(spitter);
    try {
        if (!image.isEmpty()) {
            validateImage(image);
            saveImage(spitter.getId() + ".jpg", image);
        }
    } catch (FileUploadException e) {
        bindingResult.reject(e.getMessage());
        return "spitters/edit";
    }
    return "redirect:/spitters/" + spitter.getUsername();
}
Example 52
Project: taobao88-master  File: SliderController.java View source code
@RequestMapping(value = "/createSlider/doCreate", method = RequestMethod.POST)
public String createSlider(@RequestParam("rDesc") String desc, @RequestParam("rPrice") String price, @RequestParam("rHref") String href, @RequestParam("rPhoto") MultipartFile file, @RequestParam("recType") int recType) {
    Recomendation rec = new Recomendation();
    rec.setDescription(desc);
    rec.setPrice(Double.parseDouble(price));
    rec.setHref(href);
    rec.setPhoto(saveUploadedFile(file));
    rec.setType(recomendationTypeService.getTypeById(recType));
    recomendationService.addRecomendation(rec);
    return "redirect:/admin/pageRedactor/slider";
}
Example 53
Project: webofneeds-master  File: RestNeedPhotoController.java View source code
@ResponseBody
@RequestMapping(value = "/", method = RequestMethod.POST)
public ResponseEntity uploadPhoto(@RequestParam("photo") MultipartFile photo, @RequestParam("unique") String uniqueKey, @RequestParam("selected") String selected) {
    File tempDir = new File(uniqueKey);
    if (!tempDir.exists())
        tempDir.mkdir();
    File photoTempFile = new File(tempDir, selected + "." + FilenameUtils.getExtension(photo.getOriginalFilename()));
    try {
        logger.info("Saving file to " + photoTempFile.getAbsolutePath());
        photo.transferTo(photoTempFile);
        return new ResponseEntity(HttpStatus.OK);
    } catch (IOException e) {
        return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
    }
}
Example 54
Project: xbin-store-master  File: PictureController.java View source code
@RequestMapping("/pic/upload")
@ResponseBody
public String picUpload(MultipartFile uploadFile, MultipartFile wangEditorH5File) {
    if (uploadFile != null) {
        String oName = uploadFile.getOriginalFilename();
        String extName = oName.substring(oName.indexOf(".") + 1);
        HashMap<String, Object> map = new HashMap<>();
        try {
            // String uploadUrl = FastDFSClientUtils.upload(uploadFile.getBytes(), extName);
            String uploadUrl = storageService.upload(uploadFile.getBytes(), extName);
            map.put("success", "上传�功");
            map.put("url", FASTDFS_BASE_URL + uploadUrl);
        } catch (IOException e) {
            logger.error("图片上传失败�");
            map.put("error", 1);
            map.put("message", "图片上传失败");
        }
        return FastJsonConvert.convertObjectToJSON(map);
    } else if (wangEditorH5File != null) {
        String oName = wangEditorH5File.getOriginalFilename();
        String extName = oName.substring(oName.indexOf(".") + 1);
        try {
            //String uploadUrl = FastDFSClientUtils.upload(wangEditorH5File.getBytes(), extName);
            String uploadUrl = storageService.upload(wangEditorH5File.getBytes(), extName);
            String url = FASTDFS_BASE_URL + uploadUrl;
            return url;
        } catch (IOException e) {
            logger.error("图片上传失败�");
            String error = "error|�务器端错误";
            return error;
        }
    }
    return "";
}
Example 55
Project: Consent2Share-master  File: SpiritPushC32Controller.java View source code
@RequestMapping(value = "/c32", method = RequestMethod.POST)
@ResponseBody
public String pushC32(@RequestParam("file") MultipartFile file) throws Exception {
    XdsSrcSubmitRsp response = null;
    try {
        response = spirit.submitC32(file.getBytes());
    } catch (Throwable e) {
        logger.error("Failed to push C32 to spirit repository", e);
        throw e;
    }
    if (response.getResponseDetail().getListSuccess().get(0) == null) {
        String errorMessage = "Failed to push C32 to spirit repository.";
        if (response.getResponseDetail().getListError() != null)
            logger.error(response.getResponseDetail().getListError().get(0));
        logger.error(errorMessage);
        throw new Exception(errorMessage);
    }
    return "Push C32 to spirit repository";
}
Example 56
Project: ankush-master  File: FileUploadController.java View source code
/**
	 * Upload.
	 * 
	 * @param category
	 *            the category
	 * @param multipartRequest
	 *            the multipart request
	 * @param p
	 *            the p
	 * @return the response entity
	 */
@RequestMapping(value = "uploadFile", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<ResponseWrapper<String>> upload(@RequestParam(defaultValue = "") String category, MultipartHttpServletRequest multipartRequest, Principal p) {
    MultipartFile multipartFile = (MultipartFile) multipartRequest.getFile("file");
    UploadHandler uploadHandler = new UploadHandler(multipartFile, category);
    return wrapResponse(uploadHandler.uploadFile(), HttpStatus.CREATED, HttpStatus.CREATED.toString(), "file uploaded successfully");
}
Example 57
Project: Carolina-Digital-Repository-master  File: ImportXMLController.java View source code
@RequestMapping(value = "importXML", method = RequestMethod.POST)
@ResponseBody
public Object importXML(@RequestParam("file") MultipartFile xmlFile, HttpServletRequest request) throws Exception {
    log.info("User {} has submitted a bulk metadata update package", GroupsThreadStore.getUsername());
    Map<String, String> result = new HashMap<>();
    File importFile = File.createTempFile("import", ".xml", storagePath.toFile());
    FileUtils.writeByteArrayToFile(importFile, xmlFile.getBytes());
    String emailAddress = GroupsThreadStore.getEmail();
    Job job = new Job(BulkMetadataUpdateJob.class.getName(), null, emailAddress, GroupsThreadStore.getUsername(), GroupsThreadStore.getGroups(), importFile.getAbsolutePath(), xmlFile.getOriginalFilename());
    jesqueClient.enqueue(bulkMetadataQueueName, job);
    result.put("message", "Import of metadata has begun, " + emailAddress + " will be emailed when the update completes");
    return result;
}
Example 58
Project: dss-hwcrypto-demo-master  File: SigningController.java View source code
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public Result handleUpload(@RequestParam MultipartFile file) {
    log.debug("Handling file upload for file " + file.getOriginalFilename());
    try {
        session.setUploadedFile(FileWrapper.create(file));
        return Result.resultOk();
    } catch (IOException e) {
        log.error("Error reading bytes from uploaded file " + file.getOriginalFilename(), e);
    }
    return Result.resultUploadingError();
}
Example 59
Project: easyrec-code-master  File: PluginUploadController.java View source code
@Override
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command, BindException errors) throws Exception {
    String tenantId = ServletUtils.getSafeParameter(request, "tenantId", "");
    String operatorId = ServletUtils.getSafeParameter(request, "operatorId", "");
    logger.info("PluginUploadController: submit called");
    // cast the fubean
    FileUploadBean fubean = (FileUploadBean) command;
    if (fubean == null || fubean.getFile() == null || fubean.getFile().isEmpty()) {
        logger.info("no file or empty file was uploaded, aborting");
        // well, let's do nothing with the fubean for now and return
        return super.onSubmit(request, response, command, errors);
    }
    // check if there's content there
    MultipartFile file = fubean.getFile();
    PluginVO plugin = pluginRegistry.checkPlugin(file.getBytes());
    plugin.setOrigFilename(file.getOriginalFilename());
    pluginDAO.storePlugin(plugin);
    ModelAndView mav = new ModelAndView("dev/page");
    mav.addObject("title", "easyrec :: administration");
    mav.addObject("operatorId", operatorId);
    mav.addObject("tenantId", tenantId);
    mav.addObject("signedinOperatorId", Security.signedInOperatorId(request));
    mav.addObject("page", "plugins");
    List<PluginVO> plugins = pluginDAO.loadPlugins();
    mav.addObject("pluginList", plugins);
    return mav;
// well, let's do nothing with the fubean for now and return
//return super.onSubmit(request, response, command, errors);
}
Example 60
Project: elmis-master  File: TemplateController.java View source code
@RequestMapping(value = "/report-templates", method = POST)
@PreAuthorize("@permissionEvaluator.hasPermission(principal,'MANAGE_REPORT')")
public ResponseEntity<OpenLmisResponse> createJasperReportTemplate(HttpServletRequest request, MultipartFile file, String name, String description) {
    try {
        Template template = new Template(name, null, null, CONSISTENCY_REPORT, description);
        template.setCreatedBy(loggedInUserId(request));
        templateService.validateFileAndInsertTemplate(template, file);
        return success(messageService.message(JASPER_CREATE_REPORT_SUCCESS), MediaType.TEXT_HTML_VALUE);
    } catch (IOException e) {
        return error(messageService.message(JASPER_CREATE_REPORT_ERROR), OK, MediaType.TEXT_HTML_VALUE);
    } catch (DataException e) {
        return OpenLmisResponse.error(e, OK, MediaType.TEXT_HTML_VALUE);
    }
}
Example 61
Project: evenstar-master  File: StreamingMultipartResolver.java View source code
public MultipartHttpServletRequest resolveMultipart(HttpServletRequest request) throws MultipartException {
    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload();
    upload.setFileSizeMax(maxUploadSize);
    String encoding = determineEncoding(request);
    Map<String, MultipartFile> multipartFiles = new HashMap<String, MultipartFile>();
    Map<String, String[]> multipartParameters = new HashMap<String, String[]>();
    // Parse the request
    try {
        FileItemIterator iter = upload.getItemIterator(request);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            String name = item.getFieldName();
            InputStream stream = item.openStream();
            if (item.isFormField()) {
                String value = Streams.asString(stream, encoding);
                String[] curParam = (String[]) multipartParameters.get(name);
                if (curParam == null) {
                    // simple form field
                    multipartParameters.put(name, new String[] { value });
                } else {
                    // array of simple form fields
                    String[] newParam = StringUtils.addStringToArray(curParam, value);
                    multipartParameters.put(name, newParam);
                }
            } else {
                // Process the input stream
                MultipartFile file = new StreamingMultipartFile(item);
                multipartFiles.put(name, file);
            }
        }
    } catch (IOException e) {
        throw new MultipartException("something went wrong here", e);
    } catch (FileUploadException e) {
        throw new MultipartException("something went wrong here", e);
    }
    return new DefaultMultipartHttpServletRequest(request, multipartFiles, multipartParameters);
}
Example 62
Project: funiture-master  File: FileInfoService.java View source code
public List<FileUploadBo> handleUploadFiles(List<MultipartFile> fileList, String operator) throws Exception {
    List<FileUploadBo> uploadFileList = Lists.newArrayList();
    if (CollectionUtils.isEmpty(fileList)) {
        return uploadFileList;
    }
    for (MultipartFile file : fileList) {
        //记录上传过程起始时的时间,用�计算上传时间
        int start = (int) System.currentTimeMillis();
        String fileMD5 = "";
        if (file != null) {
            //å?–得当å‰?上传文件的文件å??ç§°
            String originalFilename = file.getOriginalFilename();
            //如果å??ç§°ä¸?为“â€?,说明该文件存在,å?¦åˆ™è¯´æ˜Žè¯¥æ–‡ä»¶ä¸?存在
            if (originalFilename.trim() != "") {
                // 判断文件是�已�上传过
                fileMD5 = FileMD5Util.getMD5String(file.getBytes());
                FileInfo fileInfo = fileInfoDao.findByMD5(fileMD5);
                if (fileInfo != null) {
                    log.info("{}已�上传过,md5:{},file:{}", originalFilename, fileMD5, JsonMapper.obj2String(fileInfo));
                    uploadFileList.add(FileUploadBo.success(originalFilename, fileInfo.getName()));
                    continue;
                }
                //é‡?命å??上传å?Žçš„æ–‡ä»¶å??
                String fileName = generateFilePrefix() + getSuffix(originalFilename);
                //定义上传路径
                String path = GlobalConfig.getValue(GlobalConfigKey.FILE_UPLOAD_PATH) + fileName;
                File localFile = new File(path);
                file.transferTo(localFile);
                // 把文件上传信��存到数�库中
                fileInfo = new FileInfo(originalFilename, fileName, operator, fileMD5, file.getSize());
                asyncSaveFileInfo(fileInfo);
                uploadFileList.add(FileUploadBo.success(originalFilename, fileName));
            }
            //记录上传该文件�的时间
            long time = System.currentTimeMillis() - start;
            log.info("upload {} use time {}, size: {}, md5: {}", originalFilename, time, file.getSize(), fileMD5);
        }
    }
    return uploadFileList;
}
Example 63
Project: gerbil-master  File: FileUploadController.java View source code
@RequestMapping(value = "upload", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<UploadFileContainer> upload(MultipartHttpServletRequest request, HttpServletResponse response) {
    if (path == null) {
        logger.error("Path must be not null");
        return new ResponseEntity<UploadFileContainer>(HttpStatus.INTERNAL_SERVER_ERROR);
    }
    LinkedList<FileMeta> files = new LinkedList<FileMeta>();
    MultipartFile mpf = null;
    for (Iterator<String> it = request.getFileNames(); it.hasNext(); ) {
        mpf = request.getFile(it.next());
        logger.debug("{} uploaded", mpf.getOriginalFilename());
        FileMeta fileContainer = new FileMeta();
        fileContainer.setName(mpf.getOriginalFilename());
        fileContainer.setSize(mpf.getSize() / 1024 + "Kb");
        fileContainer.setFileType(mpf.getContentType());
        try {
            fileContainer.setBytes(mpf.getBytes());
            createFolderIfNotExists();
            FileCopyUtils.copy(mpf.getBytes(), new BufferedOutputStream(new FileOutputStream(path + mpf.getOriginalFilename())));
        // the copy method closed the output stream
        } catch (IOException e) {
            logger.error("Error during file upload", e);
            fileContainer.setError(e.getMessage());
        }
        files.add(fileContainer);
    }
    UploadFileContainer uploadFileContainer = new UploadFileContainer(files);
    return new ResponseEntity<UploadFileContainer>(uploadFileContainer, HttpStatus.OK);
}
Example 64
Project: hsweb-framework-master  File: AopAccessLoggerResolver.java View source code
public LoggerInfo resolver(ProceedingJoinPoint pjp) {
    LoggerInfo logInfo = new LoggerInfo();
    HttpServletRequest request = WebUtil.getHttpServletRequest();
    Class<?> target = pjp.getTarget().getClass();
    StringBuilder describe = new StringBuilder();
    MethodSignature methodSignature = ((MethodSignature) pjp.getSignature());
    Method method = methodSignature.getMethod();
    String methodName = AopUtils.getMethodName(pjp);
    AccessLogger classAnnotation = ClassUtils.getAnnotation(target, AccessLogger.class);
    AccessLogger methodAnnotation = ClassUtils.getAnnotation(method, AccessLogger.class);
    if (classAnnotation != null) {
        describe.append(classAnnotation.value());
    }
    if (methodAnnotation != null) {
        if (classAnnotation != null)
            describe.append("-");
        describe.append(methodAnnotation.value());
    }
    Map<String, Object> param = new LinkedHashMap<>();
    String[] paramNames = methodSignature.getParameterNames();
    Object[] args = pjp.getArgs();
    for (int i = 0; i < paramNames.length; i++) {
        Object arg = args[i];
        String argString;
        if (arg instanceof HttpServletRequest || arg instanceof HttpSession || arg instanceof HttpServletResponse || arg instanceof MultipartFile || arg instanceof MultipartFile[])
            continue;
        if (arg instanceof String)
            argString = (String) arg;
        else if (arg instanceof Number)
            argString = String.valueOf(arg);
        else if (arg instanceof Date)
            argString = DateTimeUtils.format(((Date) arg), DateTimeUtils.YEAR_MONTH_DAY_HOUR_MINUTE_SECOND);
        else {
            try {
                argString = JSON.toJSONString(arg);
            } catch (Exception e) {
                continue;
            }
        }
        param.put(paramNames[i], argString);
    }
    Map<String, String> header = WebUtil.getHeaders(request);
    logInfo.setId(MD5.encode(String.valueOf(System.nanoTime())));
    //方法æ??è¿°
    logInfo.setModuleDesc(describe.toString());
    //当å‰?访问映射到的类å??
    logInfo.setClassName(target.getName());
    //ip地�
    logInfo.setClientIp(WebUtil.getIpAddr(request));
    //方法:GET.select()
    logInfo.setRequestMethod(request.getMethod().concat(".").concat(methodName));
    //http请求头
    logInfo.setRequestHeader(JSON.toJSONString(header));
    //referer
    logInfo.setReferer(header.get("Referer"));
    //请求相对路径
    logInfo.setRequestUri(request.getRequestURI());
    //请求�对路径
    logInfo.setRequestUrl(WebUtil.getBasePath(request).concat(logInfo.getRequestUri().substring(1)));
    //客户端标识
    logInfo.setUserAgent(header.get("User-Agent"));
    //请求�数
    logInfo.setRequestParam(JSON.toJSONString(param));
    return logInfo;
}
Example 65
Project: Java-ECOM-Project-master  File: ProductImage.java View source code
@RequestMapping(value = "/product/{id}/image", method = RequestMethod.POST)
public ResponseEntity<String> create(@PathVariable("id") int productId, @RequestParam("image") MultipartFile image) {
    HttpHeaders responseHeaders = new HttpHeaders();
    responseHeaders.set("Content-type", "text/html");
    String success = null;
    String msg = null;
    String imageUrl = "";
    Product product = productFacade.find(productId);
    if (product == null) {
        success = "false";
        msg = "Ce produit n'existe pas / plus";
    }
    if (image.isEmpty()) {
        success = "false";
        msg = "Impossible de sauvegarder l'image";
    }
    if (!image.getContentType().contains("image")) {
        success = "false";
        msg = "Format de fichier non valide";
    }
    if (success == null) {
        try {
            URL thumbUrl = imageManager.uploadThumb(image.getInputStream(), 200);
            if (thumbUrl != null) {
                imageUrl = thumbUrl.toString();
                product.setImage(imageUrl);
                productFacade.edit(product);
                success = "true";
            } else {
                success = "false";
                msg = "Impossible de générer l'image";
            }
        } catch (Exception ex) {
            success = "false";
            msg = "Impossible de générer l'image : " + ex.getMessage();
        }
    }
    return new ResponseEntity<String>("{success:" + success + ",msg:\"" + msg + "\",image:\"" + imageUrl + "\"}", responseHeaders, HttpStatus.OK);
}
Example 66
Project: jcalaBlog-master  File: FileTools.java View source code
public static String updatePic(String restUrl, String picHome, HttpServletRequest request) throws Exception {
    MultipartFile multipartFile = getMultipartFile(request);
    //设置图片å??称为currentTimeMillis+文件å?Žç¼€
    String fileName = String.valueOf(System.currentTimeMillis()) + "." + FileTools.getSuffix(multipartFile.getOriginalFilename());
    //获�当�年月
    String yearMonth = TimeTools.getYearMonthOfNow();
    //图片存储路径为根路径/年月。比如user/jcala/xmarket/201608
    File path = new File(picHome + File.separatorChar + yearMonth);
    //��图片在�务器上的�对路径
    File targetFile = new File(picHome + File.separatorChar + yearMonth + File.separatorChar + fileName);
    if (!path.exists()) {
        path.mkdirs();
    }
    //�存图片
    multipartFile.transferTo(targetFile);
    return getServerRoot(request) + restUrl + yearMonth + "/" + fileName;
}
Example 67
Project: lavagna-master  File: UsersAdministrationControllerTest.java View source code
@Test
public void createUsers() throws JsonParseException, IOException {
    MultipartFile mpf = mock(MultipartFile.class);
    when(mpf.getInputStream()).thenReturn(new ByteArrayInputStream("[{\"provider\" : \"demo\", \"username\" : \"username\"}]".getBytes("UTF-8")));
    usersAdministrationController.createUsers(mpf);
    verify(userService).createUsers(Mockito.<List<UserToCreate>>any());
}
Example 68
Project: loli.io-master  File: FileUploadAction.java View source code
@RequestMapping(value = "", method = { RequestMethod.PUT, RequestMethod.POST })
@ResponseBody
public FileEntity upload(@RequestParam int folderId, @RequestParam(value = "file", required = true) MultipartFile file, HttpSession session) throws IOException {
    User user = (User) session.getAttribute("user");
    String originName = file.getOriginalFilename();
    long now = System.nanoTime();
    String email = user.getEmail();
    String strToHash = originName + now + email;
    String generatedName = null;
    try {
        generatedName = MD5Util.hash(strToHash);
    } catch (NoSuchAlgorithmException e) {
        logger.error(e);
        e.printStackTrace();
    }
    File f = this.saveFile(file, generatedName);
    StorageFile uploadedFile = storageFolders.uploadFile(f);
    FolderEntity parent = sfs.findById(folderId);
    FileEntity entity = new FileEntity();
    entity.setUser(user);
    entity.setLength(file.getSize());
    entity.setCreateDate(new Date());
    entity.setFolder(parent);
    entity.setKey(uploadedFile.getObject().getKey());
    entity.setNewName(originName);
    entity.setOriginName(originName);
    fs.save(entity);
    md5Utils.addTask(f, entity.getId());
    return entity;
}
Example 69
Project: lolibox-master  File: ImageController.java View source code
@RequestMapping("/upload")
@PreAuthorize("@adminProperties.anonymous or hasRole('USER')")
public StatusBean upload(@RequestParam(value = "image", required = true) MultipartFile imageFile, Authentication authentication) {
    String url;
    String originName = imageFile.getOriginalFilename();
    String suffix = FileUtil.getSuffix(originName);
    try (InputStream is = new BufferedInputStream(imageFile.getInputStream())) {
        Long id = idSeqRepository.save(new IdSeq()).getId();
        String name = hashids.encode(id) + ".".concat(suffix);
        String contentType = imageFile.getContentType();
        if (StringUtils.isBlank(contentType)) {
            contentType = URLConnection.guessContentTypeFromName(originName);
        }
        if (StringUtils.isBlank(contentType)) {
            contentType = "image/png";
        }
        url = service.upload(is, name, contentType, imageFile.getSize());
        ImgFile file = new ImgFile();
        file.setCreateDate(new Date());
        file.setId(id);
        file.setOriginName(originName);
        file.setShortName(url);
        file.setSize(imageFile.getSize());
        if (authentication != null && authentication.getAuthorities().stream().map(GrantedAuthority::getAuthority).anyMatch(Role.ROLE_USER.toString()::equals)) {
            file.setUser(userService.findByEmailOrName(((SocialUserDetails) authentication.getPrincipal()).getEmail()));
        }
        imgFileRepository.save(file);
    } catch (Exception e) {
        e.printStackTrace();
        return new StatusBean("error", "Error:" + e.getMessage());
    }
    if (url != null) {
        return new StatusBean("success", "images/" + url);
    } else {
        return new StatusBean("error", "Failed to upload");
    }
}
Example 70
Project: mini-blog-master  File: UserInfoManageController.java View source code
/**
     * 头�上传原始图片
     * @param model
     * @param logo
     * @param resquest
     * @return
     */
@RequestMapping(method = RequestMethod.POST, value = "upload")
@ResponseBody
public String uploadOriginalImage(ModelMap model, @RequestParam("filename") MultipartFile logo, HttpServletRequest resquest) {
    try {
        int originalwidth = FileUtil.getImageWidth(logo.getInputStream());
        String url = this.imageService.uploadOriginalFileHandle(logo.getBytes(), LoginHelper.getUserId(), logo.getOriginalFilename(), originalwidth);
        return url;
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return "null";
}
Example 71
Project: miso-lims-master  File: AjaxMultipartResolver.java View source code
@Override
public MultipartHttpServletRequest resolveMultipart(HttpServletRequest request) throws MultipartException {
    String encoding = determineEncoding(request);
    FileUpload fileUpload = prepareFileUpload(encoding);
    if (fileUploadListener != null) {
        fileUpload.setProgressListener(fileUploadListener);
        request.getSession(false).setAttribute("upload_listener", fileUploadListener);
    }
    try {
        List fileItems = ((ServletFileUpload) fileUpload).parseRequest(request);
        MultipartParsingResult parsingResult = parseFileItems(fileItems, encoding);
        Map<String, String> multipartContentTypes = new HashMap<String, String>();
        for (List<MultipartFile> files : parsingResult.getMultipartFiles().values()) {
            for (MultipartFile f : files) {
                multipartContentTypes.put(f.getName(), f.getContentType());
            }
        }
        return new DefaultMultipartHttpServletRequest(request, parsingResult.getMultipartFiles(), parsingResult.getMultipartParameters(), multipartContentTypes);
    } catch (FileUploadBase.SizeLimitExceededException ex) {
        throw new MaxUploadSizeExceededException(fileUpload.getSizeMax(), ex);
    } catch (FileUploadException ex) {
        throw new MultipartException("Could not parse multipart servlet request", ex);
    }
}
Example 72
Project: mystamps-master  File: DatabaseImagePersistenceStrategy.java View source code
@Override
public void save(MultipartFile file, ImageInfoDto image) {
    try {
        AddImageDataDbDto imageData = new AddImageDataDbDto();
        imageData.setImageId(image.getId());
        imageData.setContent(file.getBytes());
        imageData.setPreview(false);
        Integer id = imageDataDao.add(imageData);
        LOG.info("Image #{}: meta data has been saved to #{}", image.getId(), id);
    } catch (IOException e) {
        throw new ImagePersistenceException(e);
    }
}
Example 73
Project: openmrs-module-formentry-master  File: XsnUploadFormController.java View source code
/** 
	 * 
	 * The onSubmit function receives the form/command object that was modified
	 *   by the input form and saves it to the db
	 * 
	 * @see org.springframework.web.servlet.mvc.SimpleFormController#onSubmit(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object, org.springframework.validation.BindException)
	 */
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object obj, BindException errors) throws Exception {
    HttpSession httpSession = request.getSession();
    String view = getFormView();
    if (Context.isAuthenticated()) {
        Form form = null;
        try {
            // handle xsn upload
            if (request instanceof MultipartHttpServletRequest) {
                MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
                MultipartFile xsnFile = multipartRequest.getFile("xsnFile");
                if (xsnFile != null && !xsnFile.isEmpty()) {
                    form = PublishInfoPath.publishXSN(xsnFile.getInputStream());
                    String msg = getMessageSourceAccessor().getMessage("formentry.xsn.saved", new String[] { form.getName() });
                    httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, msg);
                }
            }
        } catch (IOException e) {
            log.error("Error while getting xsnFile from request", e);
            errors.reject(e.getMessage());
            httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "formentry.xsn.not.saved");
            return showForm(request, response, errors);
        }
        // redirect to the form's schema design if a successful upload occurred
        if (form != null)
            view = request.getContextPath() + "/admin/forms/formEdit.form?formId=" + form.getFormId();
        else
            view = getSuccessView();
        return new ModelAndView(new RedirectView(view));
    }
    httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "formentry.xsn.not.saved");
    return showForm(request, response, errors);
}
Example 74
Project: paoding-rose-master  File: ParameterNameDiscovererImpl.java View source code
protected String getParameterRawName(Class<?> clz) {
    if (//
    ClassUtils.isPrimitiveOrWrapper(clz) || // 
    clz == String.class || //
    Map.class.isAssignableFrom(clz) || //
    Collection.class.isAssignableFrom(clz) || //
    clz.isArray() || clz == MultipartFile.class) {
        return null;
    }
    if (clz == MultipartFile.class) {
        return null;
    }
    return ClassUtils.getShortNameAsProperty(clz);
}
Example 75
Project: phoenix.platform-master  File: AttachmentController.java View source code
@RequestMapping("upload")
public String upload(MultipartFile file, Attachment attachment, @RequestParam(value = "redirectPath") String redirectPath) {
    UserDetail userDetail = (UserDetail) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    String ownerId = userDetail.getId();
    attachment.setOwnerId(ownerId);
    attachment.setCreateTime(new Date());
    Options options = optionsMapper.getByKey("attachRoot");
    if (options != null) {
        String attachRoot = options.getOptValue();
        attachment.setRelativePath(attachRoot);
        try (InputStream input = file.getInputStream();
            OutputStream output = new FileOutputStream(new File(attachRoot, attachment.getFileName()))) {
            IOUtils.copy(input, output);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    String configId;
    List<AttachConfig> attachConfigList = attachConfigMapper.getAll();
    if (CollectionUtils.isEmpty(attachConfigList)) {
        AttachConfig config = new AttachConfig();
        config.setName("for demo");
        attachConfigMapper.save(config);
        configId = config.getId();
    } else {
        configId = attachConfigList.get(0).getId();
    }
    attachment.setConfigId(configId);
    attachmentMapper.save(attachment);
    return "redirect:" + redirectPath;
}
Example 76
Project: quadriga-master  File: UploadTransformFilesController.java View source code
@RequestMapping(value = "auth/transformation/upload", method = RequestMethod.POST)
public ModelAndView uploadTransformFiles(@Validated @ModelAttribute("transformationFilesBackingBean") TransformFilesBackingBean formBean, BindingResult result, ModelMap map, Principal principal, @RequestParam("file") MultipartFile[] file) throws IOException, QuadrigaStorageException, FileStorageException {
    ModelAndView model;
    model = new ModelAndView("auth/uploadTransformation");
    if (result.hasErrors()) {
        model.getModelMap().put("show_error_alert", true);
        model.getModelMap().put("error_alert_msg", "Please enter all the required fields.");
        return model;
    } else if (file.length != 2) {
        model.getModelMap().put("show_error_alert", true);
        model.getModelMap().put("error_alert_msg", "Please upload all the required files.");
        return model;
    } else if (file[0].getSize() == 0 || file[1].getSize() == 0) {
        model.getModelMap().put("show_error_alert", true);
        model.getModelMap().put("error_alert_msg", "Please upload all the required files.");
        return model;
    } else {
        String title = formBean.getTitle();
        String description = formBean.getDescription();
        IUser user = userManager.getUser(principal.getName());
        String userName = user.getName();
        String patternTitle = formBean.getPatternTitle();
        String patternDescription = formBean.getPatternDescription();
        String patternFileName = file[0].getOriginalFilename();
        String mappingTitle = formBean.getMappingTitle();
        String mappingDescription = formBean.getMappingDescription();
        String mappingFileName = file[1].getOriginalFilename();
        TransformationFile transformationFile = new TransformationFile();
        transformationFile.setTitle(title);
        transformationFile.setDescription(description);
        transformationFile.setUserName(userName);
        transformationFile.setPatternTitle(patternTitle);
        transformationFile.setPatternDescription(patternDescription);
        transformationFile.setPatternFileName(patternFileName);
        transformationFile.setPatternFileContent(new String(file[0].getBytes(), StandardCharsets.UTF_8));
        transformationFile.setMappingTitle(mappingTitle);
        transformationFile.setMappingDescription(mappingDescription);
        transformationFile.setMappingFileName(mappingFileName);
        transformationFile.setMappingFileContent(new String(file[1].getBytes(), StandardCharsets.UTF_8));
        transformationManager.saveTransformations(transformationFile);
        model.getModelMap().put("show_success_alert", true);
        model.getModelMap().put("success_alert_msg", "Upload Successful.");
        return model;
    }
}
Example 77
Project: spacesimulator-master  File: BuilderController.java View source code
@RequestMapping(value = "/upload")
@ResponseBody
public Builder upload(@RequestParam("file") MultipartFile file) {
    try {
        String fileName = file.getOriginalFilename();
        byte[] bytes = file.getBytes();
        Builder builder = new Builder();
        builder.setFileName(fileName);
        builder.setData(bytes);
        builder.setBuilderClassName(ByteArrayModelBuilder.class.getSimpleName());
        builder.setName("Builder from file " + fileName);
        String id = builderCollection.add(builder);
        builder.setId(id);
        logger.info("Server File Location=" + fileName);
        return builder;
    } catch (IOException e) {
        throw new IllegalArgumentException("unable to uplaod model", e);
    }
}
Example 78
Project: spring-a-gram-master  File: ApplicationController.java View source code
@RequestMapping(method = RequestMethod.POST, value = "/files")
public ResponseEntity<?> newFile(@RequestParam("name") String filename, @RequestParam("file") MultipartFile file) {
    try {
        this.fileService.saveFile(file.getInputStream(), file.getSize(), filename);
        Link link = linkTo(methodOn(ApplicationController.class).getFile(filename)).withRel(filename);
        return ResponseEntity.created(new URI(link.getHref())).build();
    } catch (IOExceptionURISyntaxException |  e) {
        return ResponseEntity.badRequest().body("Couldn't process the request");
    }
}
Example 79
Project: spring-mvc-model-attribute-alias-master  File: SuishenServletModelAttributeMethodProcessor.java View source code
protected void bindMultipart(Map<String, List<MultipartFile>> multipartFiles, MutablePropertyValues mpvs) {
    for (Map.Entry<String, List<MultipartFile>> entry : multipartFiles.entrySet()) {
        String key = entry.getKey();
        List<MultipartFile> values = entry.getValue();
        if (values.size() == 1) {
            MultipartFile value = values.get(0);
            if (!value.isEmpty()) {
                mpvs.add(key, value);
            }
        } else {
            mpvs.add(key, values);
        }
    }
}
Example 80
Project: spring-social-flickr-master  File: HomeController.java View source code
@RequestMapping(value = "/uploadphoto", method = RequestMethod.POST)
public String create(@RequestParam(value = "title", required = false) String title, @RequestParam(value = "description", required = false) String description, @RequestParam("photo") MultipartFile photo, Model model) throws Throwable {
    File tmpFile = File.createTempFile("tmp", photo.getOriginalFilename());
    OutputStream outputStream = null;
    InputStream inputStream = null;
    try {
        outputStream = new FileOutputStream(tmpFile);
        IOUtils.copy(photo.getInputStream(), outputStream);
        Assert.isTrue(tmpFile.exists() && tmpFile.length() > 0, "there must be a file to read from!");
        String photoId = flickr.photoOperations().upload(tmpFile, title, description, null, null, null, null);
        model.addAttribute("photoId", photoId);
    } finally {
        IOUtils.closeQuietly(outputStream);
        IOUtils.closeQuietly(inputStream);
        tmpFile.delete();
    }
    return "welcome";
}
Example 81
Project: spring-webflow-master  File: HttpServletRequestParameterMap.java View source code
protected Object getAttribute(String key) {
    if (request instanceof MultipartHttpServletRequest) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        List<MultipartFile> data = multipartRequest.getMultiFileMap().get(key);
        if (data != null && data.size() > 0) {
            if (data.size() == 1) {
                return data.get(0);
            } else {
                return data;
            }
        }
    }
    String[] parameters = request.getParameterValues(key);
    if (parameters == null) {
        return null;
    } else if (parameters.length == 1) {
        return parameters[0];
    } else {
        return parameters;
    }
}
Example 82
Project: springboot-mybatis-mysample-master  File: FileProcessingSampleController.java View source code
/**
	 * アップロード�れ�ファイル�情報を読����画��表示�る例.
	 * アップロード�れ�ファイル�情報�アクセス�る��{@link RequestParam}�
	 * {@link MultipartFile}�組������ンドラ�引数を宣言�る。
	 * 
	 * @param file アップロード�れ�ファイル�アクセス�る���オブジェクト
	 * @param model モデル
	 * @return ビューå??
	 */
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public String upload(@RequestParam("file") MultipartFile file, Model model) throws IOException {
    // 実際�ファイル�アップロード�れ���ェック
    if (file.isEmpty()) {
        // 画�表示を制御�る���フラグを設定
        model.addAttribute("uploaded", false);
    } else {
        // 画�表示を制御�る���フラグを設定
        model.addAttribute("uploaded", true);
        // MultipartFileを通��ファイル情報�アクセス
        model.addAttribute("fileName", file.getOriginalFilename());
        model.addAttribute("firstLine", readFirstLine(file));
    }
    return "/file/upload";
}
Example 83
Project: strongbox-master  File: ArtifactOperationsValidator.java View source code
public void checkArtifactSize(String storageId, String repositoryId, MultipartFile uploadedFile) throws ArtifactResolutionException {
    if (uploadedFile.isEmpty() || uploadedFile.getSize() == 0) {
        throw new ArtifactResolutionException("Uploaded file is empty.");
    }
    Repository repository = getConfiguration().getStorage(storageId).getRepository(repositoryId);
    long artifactMaxSize = repository.getArtifactMaxSize();
    if (artifactMaxSize > 0 && uploadedFile.getSize() > artifactMaxSize) {
        throw new ArtifactResolutionException("The size of the artifact exceeds the maximum size accepted by " + "this repository (" + uploadedFile.getSize() + "/" + artifactMaxSize + ").");
    }
}
Example 84
Project: TensionCamApp-master  File: HomeController.java View source code
/**
	 * Controller method which respondes to a POST requst. It receives a MultipartFile, which in this case is a picture.
	 * The controller writes the MultipartFile as an image to the disk. Afterwards it is executed with the analyse program.
	 * After the analysis is performed the result is sent back to the client.
	 * @throws InterruptedException 
	 */
@RequestMapping(value = "/upload", method = RequestMethod.POST)
@ResponseBody
public String handleFormUpload(@RequestParam("file") MultipartFile file) throws IOException, InterruptedException {
    Read r = new Read();
    if (!file.isEmpty()) {
        //Put the bytes into a byte array
        byte[] bytes = file.getBytes();
        //A FileOutputStream with the path where the picture should be
        FileOutputStream fos = new FileOutputStream("C:\\Users\\Martin\\Desktop\\IMG1.bmp");
        try {
            //Writes the bytes to a file, in this case "creating" the picture as a .bmp
            fos.write(bytes);
        } finally {
            fos.close();
            new CommandExecution("C:\\Users\\Martin\\SoftwareEng\\Analyse.bat");
        }
        Thread.sleep(3000);
        String result = r.reader("C:\\Users\\Martin\\Desktop\\Result.txt");
        return result;
    } else {
        //Returns this in case of empty file
        return "doesn't work";
    }
}
Example 85
Project: threadfixRack-master  File: UploadWafLogController.java View source code
@RequestMapping(method = RequestMethod.POST)
public String uploadSubmit(@PathVariable("wafId") int wafId, @RequestParam("file") MultipartFile file, ModelMap model) {
    if (wafService.loadWaf(wafId) == null) {
        log.warn(ResourceNotFoundException.getLogMessage("WAF", wafId));
        throw new ResourceNotFoundException();
    }
    if (file == null || file.getOriginalFilename() == null || file.getOriginalFilename().equals("")) {
        return "redirect:/wafs/" + wafId;
    }
    // TODO put in a check to make sure the file is in the right format
    logParserService.setFile(file);
    logParserService.setWafId(wafId);
    List<SecurityEvent> events = logParserService.parseInput();
    model.addAttribute("eventList", events);
    return "wafs/upload/success";
}
Example 86
Project: tianti-master  File: UploadController.java View source code
@RequestMapping("/uploadAttach")
public void uploadAttach(HttpServletRequest request, PrintWriter out) {
    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
    Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
    MultipartFile multipartFile = null;
    String fileName = null;
    for (Map.Entry<String, MultipartFile> set : fileMap.entrySet()) {
        // 文件å??
        multipartFile = set.getValue();
    }
    fileName = this.storeIOc(multipartRequest, multipartFile);
    out.print(fileName);
}
Example 87
Project: Trainings-master  File: FileUpDownLoadController.java View source code
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public FileLoadStatus handleFileUpload(@RequestParam String trainingId, @RequestBody MultipartFile file) {
    if (!file.isEmpty()) {
        try {
            byte[] bytes = file.getBytes();
            // Creating the directory to store file
            File dir = new File(path + File.separator + trainingId);
            if (!dir.exists())
                dir.mkdirs();
            // Create the file on server
            File serverFile = new File(dir.getAbsolutePath() + File.separator + file.getOriginalFilename());
            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
            Attachment attachment = new Attachment();
            attachment.setName(file.getOriginalFilename());
            attachment.setTraining(trainingService.getTrainingById(trainingId));
            attachmentService.addAttachmentFile(attachment);
            stream.write(bytes);
            stream.close();
            return FileLoadStatus.UPLOAD_SUCCESS;
        } catch (Exception e) {
            return FileLoadStatus.UPLOAD_FAIL;
        }
    } else {
        return FileLoadStatus.UPLOAD_EMPTY_FAIL;
    }
}
Example 88
Project: XCoLab-master  File: FileUploadController.java View source code
private ImageResponse uploadImageResponse(MultipartFile file, HttpServletRequest request, Boolean resize) {
    try {
        String path = request.getSession().getServletContext().getRealPath("/");
        path = (fileUploadPath != null) ? (fileUploadPath) : (path);
        byte[] bytes = file.getBytes();
        if (resize != null) {
            bytes = FileUploadUtil.resizeAndCropImage(ImageIO.read(new ByteArrayInputStream(bytes)), IMAGE_CROP_WIDTH_PIXELS, IMAGE_CROP_HEIGHT_PIXELS);
        }
        FileEntry fileEntry = new FileEntry();
        fileEntry.setCreateDate(new Timestamp(new Date().getTime()));
        String nameExt = file.getOriginalFilename();
        fileEntry.setFileEntryExtension((FilenameUtils.getExtension(nameExt)).toLowerCase());
        fileEntry.setFileEntrySize(bytes.length);
        fileEntry.setFileEntryName(FilenameUtils.getName(nameExt));
        fileEntry = FilesClient.createFileEntry(fileEntry, bytes, path);
        final String imageIdString = String.valueOf(fileEntry.getFileEntryId());
        return new ImageResponse(imageIdString, fileEntry.getLinkUrl(), true, "");
    } catch (IOException e) {
        return new ImageResponse(null, null, false, e.getMessage());
    }
}
Example 89
Project: swagger-maven-plugin-master  File: SpringSwaggerExtension.java View source code
private Parameter extractParameterFromAnnotation(Annotation annotation, String defaultValue, Type type) {
    Parameter parameter = null;
    if (annotation instanceof RequestParam) {
        RequestParam requestParam = (RequestParam) annotation;
        QueryParameter queryParameter = new QueryParameter().name(requestParam.value()).required(requestParam.required());
        if (!defaultValue.isEmpty()) {
            queryParameter.setDefaultValue(defaultValue);
        }
        Property schema = ModelConverters.getInstance().readAsProperty(type);
        if (schema != null) {
            queryParameter.setProperty(schema);
        }
        parameter = queryParameter;
    } else if (annotation instanceof PathVariable) {
        PathVariable pathVariable = (PathVariable) annotation;
        PathParameter pathParameter = new PathParameter().name(pathVariable.value());
        if (!defaultValue.isEmpty()) {
            pathParameter.setDefaultValue(defaultValue);
        }
        Property schema = ModelConverters.getInstance().readAsProperty(type);
        if (schema != null) {
            pathParameter.setProperty(schema);
        }
        parameter = pathParameter;
    } else if (annotation instanceof RequestHeader) {
        RequestHeader requestHeader = (RequestHeader) annotation;
        HeaderParameter headerParameter = new HeaderParameter().name(requestHeader.value()).required(requestHeader.required());
        headerParameter.setDefaultValue(defaultValue);
        Property schema = ModelConverters.getInstance().readAsProperty(type);
        if (schema != null) {
            headerParameter.setProperty(schema);
        }
        parameter = headerParameter;
    } else if (annotation instanceof CookieValue) {
        CookieValue cookieValue = (CookieValue) annotation;
        CookieParameter cookieParameter = new CookieParameter().name(cookieValue.value()).required(cookieValue.required());
        if (!defaultValue.isEmpty()) {
            cookieParameter.setDefaultValue(defaultValue);
        }
        Property schema = ModelConverters.getInstance().readAsProperty(type);
        if (schema != null) {
            cookieParameter.setProperty(schema);
        }
        parameter = cookieParameter;
    } else if (annotation instanceof RequestPart) {
        RequestPart requestPart = (RequestPart) annotation;
        FormParameter formParameter = new FormParameter().name(requestPart.value()).required(requestPart.required());
        if (!defaultValue.isEmpty()) {
            formParameter.setDefaultValue(defaultValue);
        }
        JavaType ct = constructType(type);
        Property schema;
        if (MultipartFile.class.isAssignableFrom(ct.getRawClass())) {
            schema = new FileProperty();
        } else if (ct.isContainerType() && MultipartFile.class.isAssignableFrom(ct.getContentType().getRawClass())) {
            schema = new ArrayProperty().items(new FileProperty());
        } else {
            schema = ModelConverters.getInstance().readAsProperty(type);
        }
        if (schema != null) {
            formParameter.setProperty(schema);
        }
        parameter = formParameter;
    }
    return parameter;
}
Example 90
Project: ABRAID-MP-master  File: MainController.java View source code
/**
     * Handles the output of a model run.
     * @param file The model run's outputs, as a zip file.
     * @return 204 for success, 400 for invalid parameters or 500 if server cannot start model run.
     */
@RequestMapping(value = "/handleoutputs", method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
@ResponseBody
public ResponseEntity<String> handleModelOutputs(MultipartFile file) {
    File modelRunZipFile = null;
    try {
        LOGGER.info(String.format(LOG_RECEIVED_OUTPUTS, file.getSize()));
        // Save the request body to a temporary file
        modelRunZipFile = saveRequestBodyToTemporaryFile(file);
        // Continue handling the outputs
        ModelRun modelRun = mainHandler.handleOutputs(modelRunZipFile);
        // Delete old pre-mask raster outputs (outside of the "mainHandler.handleOutputs" transaction)
        boolean deleteResult = mainHandler.handleOldRasterDeletion(modelRun.getDiseaseGroupId());
        if (!deleteResult) {
            sendCleanUpFailureEmail(modelRun);
        }
        // Announce failed model runs
        if (modelRun.getStatus() == ModelRunStatus.FAILED) {
            sendModelFailureEmail(modelRun);
        }
        // Do background post processing (e.g. validation parameter updates)
        handlersAsyncWrapper.handle(modelRun);
    } catch (Exception e) {
        LOGGER.error(e.getMessage(), e);
        if (modelRunZipFile != null) {
            try {
                mainHandler.markAsFailed(modelRunZipFile);
            } catch (Exception e1) {
                LOGGER.error(e1.getMessage(), e1);
            }
        }
        return createErrorResponse(String.format(INTERNAL_SERVER_ERROR_MESSAGE, e.getMessage()), HttpStatus.INTERNAL_SERVER_ERROR);
    } finally {
        deleteTemporaryFile(modelRunZipFile);
    }
    return createSuccessResponse();
}
Example 91
Project: azure-chat-for-java-master  File: ProfileImageRequestDAOImpl.java View source code
/**
	 * This method add the image to the profile image storage for the
	 * corresponding user.
	 */
@Override
public String saveProfileImage(MultipartFile file, String fileName) throws Exception {
    LOGGER.info("[ProfileImageRequestDAOImpl][saveProfileImage] start");
    LOGGER.debug("File Name : " + fileName);
    InputStream inputStream = null;
    URI profileImageBLOBUrl = null;
    byte[] byteArr = null;
    byteArr = file.getBytes();
    inputStream = new ByteArrayInputStream(byteArr);
    CloudBlobContainer cloudBlobContainer = AzureChatStorageUtils.getCloudBlobContainer(AzureChatConstants.PROFILE_IMAGE_CONTAINER);
    AzureChatStorageUtils.generateSASURL(cloudBlobContainer);
    CloudBlockBlob blob = cloudBlobContainer.getBlockBlobReference(fileName);
    blob.getProperties().setContentType(file.getContentType());
    blob.upload(inputStream, byteArr.length);
    profileImageBLOBUrl = blob.getUri();
    LOGGER.debug("Profile Blob URL: " + profileImageBLOBUrl);
    LOGGER.info("[ProfileImageRequestDAOImpl][saveProfileImage] end");
    return profileImageBLOBUrl + AzureChatConstants.CONSTANT_EMPTY_STRING;
}
Example 92
Project: bbks-master  File: ImageController.java View source code
@RequestMapping(value = "/uploadImage", headers = "content-type=multipart/*", produces = "text/plain;charset=UTF-8")
@ResponseBody
public String updateAvatar(HttpServletRequest request, @RequestParam(value = "Filedata", required = false) MultipartFile imageFile, @ModelAttribute("tempRepositories") String tempRepositories, Model model) {
    JsonResult jr = new JsonResult();
    if (tempRepositories == null) {
        //未登录
        jr.setIsSuccess(false);
        jr.setMessage("请登录�上传文件!");
        return jr.toJson(jr);
    }
    String orgName = imageFile.getOriginalFilename();
    String newName = getNewFileName(orgName);
    Resource res = ac.getResource(tempRepositories);
    try {
        File file = res.getFile();
        if (!file.exists()) {
            FileUtils.createDirectory(file.getPath());
            file = new File(file.getPath());
        }
        String storagePath = new StringBuffer(file.getPath()).append(File.separator).append(newName).toString();
        file = new File(storagePath);
        if (!file.exists()) {
            FileUtils.createFile(storagePath);
        }
        //this.copyFile(imageFile.getInputStream(), storagePath);
        imageFile.transferTo(file);
        jr.setIsSuccess(true);
        String imgPath = new StringBuffer("http://").append(request.getServerName()).append(":").append(request.getServerPort()).append(request.getContextPath()).append(tempRepositories).append("/").append(newName).toString();
        System.out.println("file upload ...." + imgPath);
        //			imgPath.replaceAll("\\", "/");
        jr.setObj(imgPath);
        jr.setMessage("上传文件�功�");
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        logger.error("文件上传失败�{},{}", e.getMessage(), e);
        jr.setIsSuccess(false);
        jr.setMessage("文件上传失败�");
    } catch (IOException e) {
        e.printStackTrace();
    }
    return jr.toJson(jr);
}
Example 93
Project: btpka3.github.com-master  File: FileController.java View source code
// Should not handle multi file, even should be only one file item in post data.
@RequestMapping(method = RequestMethod.POST)
public void post(@RequestParam("file") MultipartFile file, HttpServletRequest req, HttpServletResponse resp) {
    if (file == null) {
        throw new BusinessException(HttpStatus.BAD_REQUEST.value(), "for uploading, parameter name must be \"file\"");
    }
    if (file.isEmpty()) {
        throw new BusinessException(HttpStatus.BAD_REQUEST.value(), "File could not be empty");
    }
    ByteArrayResource rsc = null;
    try {
        rsc = new ByteArrayResource(file.getBytes(), file.getContentType());
    } catch (IOException e) {
        throw new BusinessException(HttpStatus.INTERNAL_SERVER_ERROR.value(), "Could not read the file uploaded.");
    }
    Long maxId = 0L;
    for (Long id : fileMap.keySet()) {
        if (id > maxId) {
            maxId = id;
        }
    }
    Long newId = maxId + 1;
    fileMap.put(newId, rsc);
    String uri = UriComponentsBuilder.newInstance().path("{contextPath}{servletPath}/file/{id}").build().expand(urlPathHelper.getContextPath(req), urlPathHelper.getServletPath(req), newId).encode().toUriString();
    resp.setHeader("Location", uri);
    resp.setStatus(HttpStatus.CREATED.value());
}
Example 94
Project: buendia-master  File: CreateChildServlet.java View source code
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    HttpSession session = request.getSession();
    if (!Context.isAuthenticated()) {
        reply(response, "Not logged in, please login and retry again", "red");
        return;
    }
    if (!Context.hasPrivilege(SyncConstants.PRIV_BACKUP_ENTIRE_DATABASE)) {
        session.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "Privilege required: " + SyncConstants.PRIV_BACKUP_ENTIRE_DATABASE);
        session.setAttribute(WebConstants.OPENMRS_LOGIN_REDIRECT_HTTPSESSION_ATTR, request.getRequestURI() + "?" + request.getQueryString());
        response.sendRedirect(request.getContextPath() + "/login.htm");
        return;
    }
    response.setContentType("text/html");
    MultipartHttpServletRequest multipartRequest = multipartResolver.resolveMultipart(request);
    MultipartFile mf = multipartRequest.getFile("cloneFile");
    if (mf != null && !mf.isEmpty()) {
        try {
            File dir = SyncUtil.getSyncApplicationDir();
            File file = new File(dir, SyncConstants.CLONE_IMPORT_FILE_NAME + SyncConstants.SYNC_FILENAME_MASK.format(new Date()) + ".sql");
            IOUtils.copy(mf.getInputStream(), new FileOutputStream(file));
            Context.getService(SyncService.class).execGeneratedFile(file);
            reply(response, "Child database successfully updated", "green");
            boolean clonedDBLog = Boolean.parseBoolean(Context.getAdministrationService().getGlobalProperty(SyncConstants.PROPERTY_SYNC_CLONED_DATABASE_LOG_ENABLED, "true"));
            if (!clonedDBLog) {
                file.delete();
            }
        } catch (Exception ex) {
            log.warn("Unable to read the clone data file", ex);
            reply(response, "Unable to read the data clonefile" + ex.toString(), "red");
            ex.printStackTrace();
        }
    } else {
        reply(response, "The file sent is null or empty, please select a file to upload", "red");
    }
}
Example 95
Project: c24-spring-master  File: IoUnmarshallingTransformerIUTests.java View source code
@Test
public void canUnmarshalTextFromMultipartFile() throws Exception {
    byte[] valid1 = loadCsvBytes();
    MultipartFile file = mock(MultipartFile.class);
    when(file.getInputStream()).thenReturn(new ByteArrayInputStream(valid1));
    C24UnmarshallingTransformer transformer = new C24UnmarshallingTransformer(model, new TextualSourceFactory());
    Message message = MessageBuilder.withPayload(file).build();
    Message<?> outputMessage = transformer.transform(message);
    assertThat(outputMessage.getPayload(), notNullValue());
    assertThat(outputMessage.getPayload(), instanceOf(Employees.class));
    Employees employees = (Employees) outputMessage.getPayload();
}
Example 96
Project: ccshop-master  File: FileUtils.java View source code
/**
	 * 多文件上传�存
	 * @param request
	 * @return
	 */
public static Map<String, File> saveMultipartFiles(HttpServletRequest request, String phone) {
    Map<String, File> files = new HashMap<String, File>();
    //创建一个通用的多部分解�器
    CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
    // 判断 request 是�有文件上传,�多部分请求
    if (multipartResolver.isMultipart(request)) {
        // 转��多部分request
        MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
        // å?–å¾—request中的所有文件å??
        Iterator<String> iter = multiRequest.getFileNames();
        while (iter.hasNext()) {
            // �得上传文件
            MultipartFile multiFile = multiRequest.getFile(iter.next());
            if (multiFile != null && !multiFile.isEmpty()) {
                // é‡?命å??上传å?Žçš„æ–‡ä»¶å??
                String fileName = FileUtils.getRandomFileName(multiFile.getOriginalFilename());
                // 定义上传路径
                File uploadDir = new File(FileUtils.getRootPath(), "uploads");
                uploadDir = new File(uploadDir, phone);
                uploadDir.mkdir();
                // 接收并�存上传的文件
                final File uploadFile = new File(uploadDir, fileName);
                try {
                    multiFile.transferTo(uploadFile);
                    files.put(multiFile.getName(), uploadFile);
                    // 异步执行图片压缩
                    executor.execute(new Runnable() {

                        @Override
                        public void run() {
                            Pic pic = new Pic(uploadFile);
                            pic.resizeBy(Config.MAX_IMAGE_WIDTH, Config.MAX_IMAGE_HEIGHT);
                            pic.save();
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
    return files;
}
Example 97
Project: cloudify-master  File: RESTRequestExampleGenerator.java View source code
private Object getRequestExample(final Class<?> clazz) {
    Object example = null;
    if (clazz.equals(InstallApplicationRequest.class)) {
        InstallApplicationRequest installApplicationRequest = new InstallApplicationRequest();
        installApplicationRequest.setApplcationFileUploadKey(RESTExamples.getUploadKey());
        installApplicationRequest.setApplicationName(RESTExamples.getAppName());
        installApplicationRequest.setApplicationOverridesUploadKey(RESTExamples.getUploadKey());
        installApplicationRequest.setAuthGroups(RESTExamples.getAuthGroup());
        installApplicationRequest.setCloudConfigurationUploadKey(RESTExamples.getUploadKey());
        installApplicationRequest.setCloudOverridesUploadKey(RESTExamples.getUploadKey());
        installApplicationRequest.setDebugAll(RESTExamples.isDebugAll());
        installApplicationRequest.setDebugEvents(RESTExamples.getDebugEvents());
        installApplicationRequest.setDebugMode(RESTExamples.getDebugMode());
        installApplicationRequest.setSelfHealing(RESTExamples.isSelfHealing());
        example = installApplicationRequest;
    } else if (clazz.equals(InstallServiceRequest.class)) {
        InstallServiceRequest installServiceRequest = new InstallServiceRequest();
        installServiceRequest.setAuthGroups(RESTExamples.getAuthGroup());
        installServiceRequest.setCloudConfigurationUploadKey(RESTExamples.getUploadKey());
        installServiceRequest.setCloudOverridesUploadKey(RESTExamples.getUploadKey());
        installServiceRequest.setDebugAll(RESTExamples.isDebugAll());
        installServiceRequest.setDebugEvents(RESTExamples.getDebugEvents());
        installServiceRequest.setDebugMode(RESTExamples.getDebugMode());
        installServiceRequest.setSelfHealing(RESTExamples.isSelfHealing());
        installServiceRequest.setServiceFileName(RESTExamples.getServiceFileName());
        installServiceRequest.setServiceFolderUploadKey(RESTExamples.getUploadKey());
        installServiceRequest.setServiceOverridesUploadKey(RESTExamples.getUploadKey());
        example = installServiceRequest;
    } else if (clazz.equals(SetApplicationAttributesRequest.class)) {
        example = new SetApplicationAttributesRequest();
        ((SetApplicationAttributesRequest) example).setAttributes(RESTExamples.getAttributes());
    } else if (clazz.equals(SetServiceAttributesRequest.class)) {
        example = new SetServiceAttributesRequest();
        ((SetServiceAttributesRequest) example).setAttributes(RESTExamples.getAttributes());
    } else if (clazz.equals(SetServiceInstanceAttributesRequest.class)) {
        example = new SetServiceInstanceAttributesRequest();
        ((SetServiceInstanceAttributesRequest) example).setAttributes(RESTExamples.getAttributes());
    } else if (clazz.equals(UpdateApplicationAttributeRequest.class)) {
        example = new UpdateApplicationAttributeRequest();
        ((UpdateApplicationAttributeRequest) example).setValue(RESTExamples.getAttribute());
    } else if (SetServiceInstancesRequest.class.equals(clazz)) {
        SetServiceInstancesRequest setServiceInstancesRequest = new SetServiceInstancesRequest();
        setServiceInstancesRequest.setCount(2);
        setServiceInstancesRequest.setLocationAware(false);
        setServiceInstancesRequest.setTimeout(RESTExamples.getTimeoutMinutes());
        example = setServiceInstancesRequest;
    } else if (AddTemplatesRequest.class.equals(clazz)) {
        example = new AddTemplatesRequest();
        ((AddTemplatesRequest) example).setUploadKey(RESTExamples.getUploadKey());
    } else if (MultipartFile.class.isAssignableFrom(clazz)) {
        example = "file's content";
    } else if (clazz.isPrimitive()) {
        example = PrimitiveExampleValues.getValue(clazz);
    } else if (clazz.equals(String.class)) {
        example = "string";
    } else {
        String className = clazz.getName();
        logger.warning("Missing custom instantiation of class " + className + " for generating request example, using newInstance instead.");
        try {
            return clazz.newInstance();
        } catch (Exception e) {
            String errMsg = "failed to instantiate " + className;
            logger.warning(errMsg);
            throw new IllegalArgumentException(errMsg);
        }
    }
    return example;
}
Example 98
Project: copartner-master  File: MediaServiceImpl.java View source code
@Override
public Map<String, String> uploadImage(MultipartFile imageFile, boolean needThumbnail) throws CException {
    String fileType = FileUtil.getFileType(imageFile.getOriginalFilename());
    InputStream in = null;
    if (needThumbnail) {
        try {
            BufferedImage image = ImageIO.read(imageFile.getInputStream());
            int imageWidth = image.getWidth();
            int imageHeitht = image.getHeight();
            int a = CommonConstant.IMAGE_STANDARD;
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            Builder<BufferedImage> builder = null;
            if (1.0f != (float) imageWidth / imageHeitht) {
                if (imageWidth > imageHeitht) {
                    image = Thumbnails.of(imageFile.getInputStream()).height(a).asBufferedImage();
                } else {
                    image = Thumbnails.of(imageFile.getInputStream()).width(a).asBufferedImage();
                }
                builder = Thumbnails.of(image).sourceRegion(Positions.CENTER, a, a).size(a, a);
            } else {
                builder = Thumbnails.of(image).size(a, a);
            }
            builder.outputFormat(fileType).toOutputStream(out);
            in = new ByteArrayInputStream(out.toByteArray());
        } catch (Exception e) {
            throw CExceptionFactory.getException(CException.class, ResponseCode.FILE_UPLOAD_ERROR);
        }
    } else {
        Map<String, String> siteSettings = SystemUtil.getSettings(SettingConstant.GROUP_TYPE_IMAGE);
        if (null != siteSettings && siteSettings.size() > 0) {
            long maxSize = FileUtil.string2bytes(siteSettings.get(SettingConstant.IMAGE_MAX_SIZE));
            long minSize = FileUtil.string2bytes(siteSettings.get(SettingConstant.IMAGE_MIN_SIZE));
            String[] imageTyps = siteSettings.get(SettingConstant.IMAGE_TYPE_LIMIT).split(",");
            int maxWidth = Integer.valueOf(siteSettings.get(SettingConstant.IMAGE_DIMENSION_MAX_WIDTH));
            int maxHeight = Integer.valueOf(siteSettings.get(SettingConstant.IMAGE_DIMENSION_MAX_HEIGHT));
            int minWidth = Integer.valueOf(siteSettings.get(SettingConstant.IMAGE_DIMENSION_MIN_WIDTH));
            int minHeight = Integer.valueOf(siteSettings.get(SettingConstant.IMAGE_DIMENSION_MIN_HEIGHT));
            FileUtil.validateImage(imageFile, maxSize, minSize, imageTyps, maxWidth, minWidth, maxHeight, minHeight);
        }
        try {
            in = imageFile.getInputStream();
        } catch (IOException e) {
            throw CExceptionFactory.getException(CException.class, ResponseCode.FILE_UPLOAD_ERROR);
        }
    }
    String fileName = new StringBuilder().append(UUID.randomUUID()).append(".").append(fileType).toString();
    String path = CDNUtil.uploadFile(in, fileName);
    Map<String, String> result = new HashMap<String, String>();
    result.put(CommonConstant.IMAGE_PATH, path);
    result.put(CommonConstant.ORIGINAL_IMAGE_URL, CDNUtil.getFullPath(path));
    return result;
}
Example 99
Project: dk-master  File: Tempontroller.java View source code
/**
	 * 修改 图片资料
	 * @param request
	 * @author zhengyfmf
	 * @return  ,LoanPersonDo loanPersonDo,Model model
	 */
@RequestMapping(value = "/saveCertificate")
@SuppressWarnings("unchecked")
public String saveOrUpdateCertificate(@RequestParam MultipartFile[] files) {
    System.out.println(files.length);
    //	Map<String, String> params = (Map<String, String>) request.getSession().getAttribute(WebConstants.COLOURLIFE_ADMIN_USER);
    try {
        System.out.println("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^");
        for (int i = 0; i < files.length; i++) {
            System.out.println(files[i].getOriginalFilename());
            String filePath = fileServerService.saveFile(files[i].getInputStream(), files[i].getOriginalFilename(), new int[][] { { 400, 400 } });
            System.out.println("file " + i + " :" + filePath);
        }
        System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
    } catch (IOException e) {
        e.printStackTrace();
    }
    /*CertificateDo certificateDo = null;
        String filePath = null;
		try {
			if (certificateDoList == null) {
				certificateDoList = new ArrayList<CertificateDo>();
				for (int i = 0; i < files.size(); i++) {
					filePath = fileServerService.saveFile(files.get(i).getInputStream(), files.get(i).getOriginalFilename(),new int[][] { { 400, 400 } });
					certificateDo = new CertificateDo();
					certificateDo.setLoanId(loanPersonDo.getLoanId());
					certificateDo.setLoanPersonId(loanPersonDo.getLoanPersonId());
					certificateDo.setFilePath(filePath);
					certificateDo.setCreateUser(params.get("userName"));// 之��获�值填充
					certificateDo.setCertificateName(files.get(i).getOriginalFilename());
					if (i == 0) {
						certificateDo.setCertificateType(CertificateType.IDCARDZ);
					} else if (i == 1) {
						certificateDo.setCertificateType(CertificateType.IDCARDF);
					} else if (i == 2) {
						certificateDo.setCertificateType(CertificateType.HOUSE);
					} else if (i == 3) {
						certificateDo.setCertificateType(CertificateType.JOB);
					} else if (i == 4) {
						certificateDo.setCertificateType(CertificateType.INCOME);
					} else{
						certificateDo.setCertificateType(CertificateType.OTHERFILE);
					}
					certificateDo.setFileType(FileType.IMAGE);
					certificateDoList.add(certificateDo);
				}
			}else{
				int count = 0;
	            for (int i = 0; i < certificateDoList.size(); i++) {
	                certificateDo = certificateDoList.get(i);
	                if ("".equals(certificateDo.getFilePath()) || certificateDo.getFilePath() == null) {
	                    filePath = fileServerService.saveFile(files.get(count).getInputStream(), files.get(count).getOriginalFilename(),new int[][] { { 400, 400 } });
	                    certificateDo.setCertificateName(files.get(count).getOriginalFilename());
	                    count++;
	                }
	                certificateDo.setCreateUser(params.get("userName"));// 之��获�值填充
	            }
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		loanPersonService.saveOrUpdateCertificate(certificateDoList);
		*/
    return "";
}
Example 100
Project: eGov-master  File: OfficialsComplaintRegistrationController.java View source code
@RequestMapping(value = "register", method = POST)
public String registerComplaint(@Valid @ModelAttribute final Complaint complaint, final BindingResult resultBinder, final RedirectAttributes redirectAttributes, @RequestParam("files") final MultipartFile[] files, final Model model) {
    if (null != complaint.getCrossHierarchyId()) {
        final CrossHierarchy crosshierarchy = crossHierarchyService.findById(complaint.getCrossHierarchyId());
        complaint.setLocation(crosshierarchy.getParent());
        complaint.setChildLocation(crosshierarchy.getChild());
    }
    if (complaint.getLocation() == null && (complaint.getLat() == 0 || complaint.getLng() == 0))
        resultBinder.rejectValue("location", "location.required");
    if (resultBinder.hasErrors()) {
        if (null != complaint.getCrossHierarchyId())
            model.addAttribute("crossHierarchyLocation", complaint.getChildLocation().getName() + " - " + complaint.getLocation().getName());
        return "complaint/officials/registration-form";
    }
    try {
        complaint.setSupportDocs(fileStoreUtils.addToFileStore(files, PGRConstants.MODULE_NAME, true));
        complaintService.createComplaint(complaint);
    } catch (final ValidationException e) {
        resultBinder.rejectValue("location", e.getMessage());
        return "complaint/officials/registration-form";
    }
    redirectAttributes.addFlashAttribute("complaint", complaint);
    return "redirect:/complaint/reg-success?crn=" + complaint.getCrn();
}
Example 101
Project: enhanced-snapshots-master  File: InitController.java View source code
/**
     * Upload idp metadata & saml sp certificate
     */
@RequestMapping(value = "/configuration/uploadFiles", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<String> uploadSSOFiles(@RequestParam("name") String name[], @RequestParam("file") MultipartFile[] file) throws Exception {
    if (name.length != 2 && file.length != name.length) {
        return new ResponseEntity<>("Failed to upload files. Saml certificate and IDP metadata should be provided", HttpStatus.BAD_REQUEST);
    }
    if (name[0].equals(idpMetadata) && name[1].equals(samlCertPem)) {
        initConfigurationService.saveAndProcessSAMLFiles(file[1], file[0]);
    } else if (name[0].equals(samlCertPem) && name[0].equals(idpMetadata)) {
        initConfigurationService.saveAndProcessSAMLFiles(file[0], file[1]);
    } else {
        return new ResponseEntity<>("Failed to upload SAML files. Saml certificate and IDP metadata should be provided", HttpStatus.BAD_REQUEST);
    }
    return new ResponseEntity<>("File uploaded successfully", HttpStatus.OK);
}