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

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

Introduction

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

Prototype

String getName();

Source Link

Document

Return the name of the parameter in the multipart form.

Usage

From source file:cz.zcu.kiv.eegdatabase.webservices.rest.datafile.DataFileServiceController.java

/**
 * Creates new DataFile under specified experiment.
 * In response is hidden url for file download.
 *
 * @param experimentId experiment identifier
 * @param description  data file description
 * @param file         data file multipart
 * @throws RestServiceException error while creating record
 *///from   w w w  . java  2 s. c  o m
@RequestMapping(method = RequestMethod.POST)
@ResponseStatus(HttpStatus.CREATED)
public void create(HttpServletRequest request, HttpServletResponse response,
        @RequestParam("experimentId") int experimentId, @RequestParam("description") String description,
        @RequestParam("file") MultipartFile file) throws RestServiceException {
    try {
        int pk = dataFileService.create(experimentId, description, file);
        response.addHeader("Location", buildLocation(request, pk));
        log.debug("File upload detected: " + file.getName());
    } catch (IOException e) {
        log.error("File upload failed: " + file.getName());
        throw new RestServiceException(e);
    }
}

From source file:org.iti.agrimarket.view.UserController.java

@RequestMapping(value = { "/uprofile.htm" }, method = RequestMethod.POST)
public String updateUserProfile(@RequestParam(value = "fullName", required = true) String fullName,
        @RequestParam(value = "mobile", required = true) String mobil,
        @RequestParam(value = "governerate", required = true) String governerate,
        @RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request,
        Locale locale, Model model) {
    System.out.println("hhhhhhhhhhhhhhhhhhhhhh" + file.getName());

    String language = locale.getLanguage();
    locale = LocaleContextHolder.getLocale();
    User user = (User) request.getSession().getAttribute("user");
    if (user != null) {
        user.setFullName(fullName);/* w  w  w. j a va 2 s.com*/
        user.setGovernerate(governerate);
        if (file != null) {
            try {
                user.setImage(file.getBytes());
                byte[] image = user.getImage();

                MagicMatch match = null;
                try {
                    match = Magic.getMagicMatch(image);
                } catch (MagicParseException ex) {
                    Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, null, ex);
                } catch (MagicMatchNotFoundException ex) {
                    Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, null, ex);
                } catch (MagicException ex) {
                    Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, null, ex);
                }
                String ext = null;
                if (match != null)
                    ext = "." + match.getExtension();

                File parentDir = new File(Constants.IMAGE_PATH + Constants.USER_PATH);
                if (!parentDir.isDirectory()) {
                    parentDir.mkdirs();
                }
                BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(
                        new File(Constants.IMAGE_PATH + Constants.USER_PATH + file.getOriginalFilename())));
                stream.write(image);
                stream.close();
                user.setImageUrl(
                        Constants.IMAGE_PRE_URL + Constants.USER_PATH + file.getOriginalFilename() + ext);

            } catch (IOException ex) {
                Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        user.setMobile(mobil);
        int res = userService.updateUser(user);
        if (res != 0) {

            request.getSession().setAttribute("user", user);
        }
        model.addAttribute("user", user);
    }
    model.addAttribute("lang", locale);

    return "profile";
}

From source file:cherry.foundation.async.AsyncFileProcessHandlerImpl.java

/**
 * ?????/*from  ww  w . j a  v a2  s .  c o m*/
 *
 * @param launcherId ?????ID
 * @param description 
 * @param file ??
 * @param handlerName ????????Bean?????Bean?{@link FileProcessHandler}???????
 * @param args 
 * @return ??????ID
 */
@Override
public long launchFileProcess(String launcherId, String description, MultipartFile file, String handlerName,
        String... args) {

    long asyncId = asyncProcessStore.createFileProcess(launcherId, bizDateTime.now(), description,
            file.getName(), file.getOriginalFilename(), file.getContentType(), file.getSize(), handlerName,
            args);
    try {

        File tempFile = createFile(file);

        Map<String, String> message = new HashMap<>();
        message.put(ASYNCID, String.valueOf(asyncId));
        message.put(FILE, tempFile.getAbsolutePath());
        message.put(NAME, file.getName());
        message.put(ORIGINAL_FILENAME, file.getOriginalFilename());
        message.put(CONTENT_TYPE, file.getContentType());
        message.put(SIZE, String.valueOf(file.getSize()));
        message.put(HANDLER_NAME, handlerName);
        for (int i = 0; i < args.length; i++) {
            message.put(String.valueOf(i), args[i]);
        }
        jmsOperations.convertAndSend(message, messagePostProcessor);

        asyncProcessStore.updateToLaunched(asyncId, bizDateTime.now());
        return asyncId;
    } catch (IOException ex) {
        asyncProcessStore.finishWithException(asyncId, bizDateTime.now(), ex);
        throw new IllegalStateException(ex);
    }
}

From source file:org.fon.documentmanagementsystem.controllers.DocumentController.java

private boolean daLiJePrazan(MultipartFile file) {
    if (file.isEmpty()) {
        System.out.println("Fajl prazan");
        return true;
    } else {/*from   w  w w .  ja v  a  2s.  c om*/
        System.out.println("naziv:" + file.getName());
    }
    return false;
}

From source file:com.slience.controller.PictureOfMongoStoreController.java

@RequestMapping(value = "/upload", method = RequestMethod.POST)
public @ResponseBody String handleFileUpload(@RequestParam("name") String name,
        @RequestParam("file") MultipartFile file) {
    if (!file.isEmpty()) {
        try {//  w  w  w  .jav  a2 s  .  c  o m
            //byte[] bytes = file.getBytes();
            //BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(name)));
            //stream.write(bytes);
            //stream.close();

            System.out.println("------------------------>" + file.getName() + ":" + file.getSize());

            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.";
    }
}

From source file:cherry.foundation.async.AsyncFileProcessHandlerImplTest.java

@Test
public void testLaunchFileProcess_IOException() throws Exception {

    AsyncFileProcessHandlerImpl impl = createImpl();

    LocalDateTime now = LocalDateTime.now();
    when(bizDateTime.now()).thenReturn(now);
    when(asyncProcessStore.createFileProcess("a", now, "b", "c", "d", "e", 100L, "f")).thenReturn(10L);

    IOException ioException = new IOException();
    MultipartFile file = mock(MultipartFile.class);
    when(file.getName()).thenReturn("c");
    when(file.getOriginalFilename()).thenReturn("d");
    when(file.getContentType()).thenReturn("e");
    when(file.getSize()).thenReturn(100L);
    when(file.getInputStream()).thenThrow(ioException);

    try {//from  ww  w.  j a  v a  2 s .  c o  m
        impl.launchFileProcess("a", "b", file, "f");
        fail("Exception must be thrown");
    } catch (IllegalStateException ex) {
        assertEquals(ioException, ex.getCause());
    }
}

From source file:cherry.foundation.async.AsyncFileProcessHandlerImplTest.java

@Test
public void testLaunchFileProcess_exception() throws Exception {

    AsyncFileProcessHandlerImpl impl = createImpl();

    LocalDateTime now = LocalDateTime.now();
    when(bizDateTime.now()).thenReturn(now);
    when(asyncProcessStore.createFileProcess("a", now, "b", "c", "d", "e", 100L, "f")).thenReturn(10L);

    IOException exception = new IOException();
    InputStream in = mock(InputStream.class);
    when(in.read((byte[]) any())).thenThrow(exception);

    MultipartFile file = mock(MultipartFile.class);
    when(file.getName()).thenReturn("c");
    when(file.getOriginalFilename()).thenReturn("d");
    when(file.getContentType()).thenReturn("e");
    when(file.getSize()).thenReturn(100L);
    when(file.getInputStream()).thenReturn(in);

    try {//  www  .ja  va  2 s .  co m
        impl.launchFileProcess("a", "b", file, "f");
        fail("Exception must be thrown");
    } catch (IllegalStateException ex) {
        verify(asyncProcessStore).createFileProcess("a", now, "b", "c", "d", "e", 100L, "f");
        verify(asyncProcessStore).finishWithException(10L, now, exception);
    }
}

From source file:cherry.foundation.async.AsyncFileProcessHandlerImplTest.java

@Test
public void testLaunchFileProcess_NO_ARG() throws Exception {

    AsyncFileProcessHandlerImpl impl = createImpl();

    LocalDateTime now = LocalDateTime.now();
    when(bizDateTime.now()).thenReturn(now);
    when(asyncProcessStore.createFileProcess("a", now, "b", "c", "d", "e", 100L, "f")).thenReturn(10L);

    MultipartFile file = mock(MultipartFile.class);
    when(file.getName()).thenReturn("c");
    when(file.getOriginalFilename()).thenReturn("d");
    when(file.getContentType()).thenReturn("e");
    when(file.getSize()).thenReturn(100L);
    when(file.getInputStream()).thenReturn(new ByteArrayInputStream(new byte[0]));

    @SuppressWarnings("rawtypes")
    ArgumentCaptor<Map> message = ArgumentCaptor.forClass(Map.class);

    long asyncId = impl.launchFileProcess("a", "b", file, "f");
    assertEquals(10L, asyncId);//from w  w w .  j  a  va2  s .  com
    verify(jmsOperations).convertAndSend(message.capture(), eq(messagePostProcessor));
    assertEquals("10", message.getValue().get("asyncId"));
    String fileName = (String) message.getValue().get("file");
    assertTrue(fileName.startsWith((new File(tempDir, "prefix_")).getAbsolutePath()));
    assertTrue(fileName.endsWith(".csv"));
    assertEquals("c", message.getValue().get("name"));
    assertEquals("d", message.getValue().get("originalFilename"));
    assertEquals("e", message.getValue().get("contentType"));
    assertEquals("100", message.getValue().get("size"));
    assertEquals("f", message.getValue().get("handlerName"));
    verify(asyncProcessStore).createFileProcess("a", now, "b", "c", "d", "e", 100L, "f");
    verify(asyncProcessStore).updateToLaunched(10L, now);
}

From source file:cherry.foundation.async.AsyncFileProcessHandlerImplTest.java

@Test
public void testLaunchFileProcess_2_ARGS() throws Exception {

    AsyncFileProcessHandlerImpl impl = createImpl();

    LocalDateTime now = LocalDateTime.now();
    when(bizDateTime.now()).thenReturn(now);
    when(asyncProcessStore.createFileProcess("a", now, "b", "c", "d", "e", 100L, "f", "g", "h"))
            .thenReturn(10L);/* www  . j  av a 2s  .  c  om*/

    MultipartFile file = mock(MultipartFile.class);
    when(file.getName()).thenReturn("c");
    when(file.getOriginalFilename()).thenReturn("d");
    when(file.getContentType()).thenReturn("e");
    when(file.getSize()).thenReturn(100L);
    when(file.getInputStream()).thenReturn(new ByteArrayInputStream(new byte[0]));

    @SuppressWarnings("rawtypes")
    ArgumentCaptor<Map> message = ArgumentCaptor.forClass(Map.class);

    long asyncId = impl.launchFileProcess("a", "b", file, "f", "g", "h");
    assertEquals(10L, asyncId);
    verify(jmsOperations).convertAndSend(message.capture(), eq(messagePostProcessor));
    assertEquals("10", message.getValue().get("asyncId"));
    String fileName = (String) message.getValue().get("file");
    assertTrue(fileName.startsWith((new File(tempDir, "prefix_")).getAbsolutePath()));
    assertTrue(fileName.endsWith(".csv"));
    assertEquals("c", message.getValue().get("name"));
    assertEquals("d", message.getValue().get("originalFilename"));
    assertEquals("e", message.getValue().get("contentType"));
    assertEquals("100", message.getValue().get("size"));
    assertEquals("f", message.getValue().get("handlerName"));
    assertEquals("g", message.getValue().get("0"));
    assertEquals("h", message.getValue().get("1"));
    verify(asyncProcessStore).createFileProcess("a", now, "b", "c", "d", "e", 100L, "f", "g", "h");
    verify(asyncProcessStore).updateToLaunched(10L, now);
}

From source file:com.glaf.mail.web.springmvc.MailTaskController.java

@RequestMapping("/uploadMails")
public ModelAndView uploadMails(HttpServletRequest request, ModelMap modelMap) {
    MultipartHttpServletRequest req = (MultipartHttpServletRequest) request;
    Map<String, Object> params = RequestUtils.getParameterMap(req);
    logger.debug(params);/*from w w w  .jav  a2  s . c  o m*/
    // System.out.println(params);
    String taskId = req.getParameter("taskId");
    if (StringUtils.isEmpty(taskId)) {
        taskId = req.getParameter("id");
    }
    MailTask mailTask = null;
    if (StringUtils.isNotEmpty(taskId)) {
        mailTask = mailTaskService.getMailTask(taskId);
    }

    if (mailTask != null && StringUtils.equals(RequestUtils.getActorId(request), mailTask.getCreateBy())) {

        try {
            Map<String, MultipartFile> fileMap = req.getFileMap();
            Set<Entry<String, MultipartFile>> entrySet = fileMap.entrySet();
            for (Entry<String, MultipartFile> entry : entrySet) {
                MultipartFile mFile = entry.getValue();
                if (mFile.getOriginalFilename() != null && mFile.getSize() > 0) {
                    logger.debug(mFile.getName());
                    if (mFile.getOriginalFilename().endsWith(".txt")) {
                        byte[] bytes = mFile.getBytes();
                        String rowIds = new String(bytes);
                        List<String> addresses = StringTools.split(rowIds);
                        if (addresses.size() <= 100000) {
                            mailDataFacede.saveMails(taskId, addresses);
                        } else {
                            throw new RuntimeException("mail addresses too many");
                        }
                        break;
                    }
                }
            }
        } catch (Exception ex) {// ?
            ex.printStackTrace();
            throw new RuntimeException(ex.getMessage());
        }
    }
    return this.mailList(request, modelMap);
}