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

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

Introduction

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

Prototype

byte[] getBytes() throws IOException;

Source Link

Document

Return the contents of the file as an array of bytes.

Usage

From source file:ua.aits.Carpath.controller.FileUploadController.java

@RequestMapping(value = { "/system/uploadPanorama",
        "/Carpath/system/uploadPanorama" }, method = RequestMethod.POST)
public @ResponseBody String uploadFileHandlerPanorama(@RequestParam("upload") MultipartFile file,
        HttpServletRequest request) {/*w  w  w. ja v a2 s. c  o  m*/

    String name = file.getOriginalFilename();
    if (!file.isEmpty()) {
        try {
            byte[] bytes = file.getBytes();
            // Creating the directory to store file
            File dir = new File(Constants.HOME + "files/panoramas/");

            File serverFile = new File(dir.getAbsolutePath() + File.separator + name);
            try (BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile))) {
                stream.write(bytes);
            }
            return 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:ua.aits.Carpath.controller.SystemController.java

@RequestMapping(value = { "/system/user/do/insertdata.do",
        "/Carpath/system/user/do/insertdata.do" }, method = RequestMethod.POST)
public ModelAndView doAddUser(@RequestParam("user_avatar") MultipartFile file, HttpServletRequest request)
        throws SQLException, ClassNotFoundException, InstantiationException, IllegalAccessException,
        UnsupportedEncodingException {
    request.setCharacterEncoding("UTF-8");
    String user_name = request.getParameter("user_name");
    String user_password = request.getParameter("user_password");
    String user_role = request.getParameter("user_role");
    String user_enabled = request.getParameter("user_enabled");
    String user_firstname = request.getParameter("user_firstname");
    String user_lastname = request.getParameter("user_lastname");
    String user_descr = request.getParameter("user_descr");
    String user_contacts = request.getParameter("user_contacts");
    String name = file.getOriginalFilename();
    String user_avatar = "";
    if (!file.isEmpty()) {
        try {//from   ww  w  .  j  a  v a  2s .  co  m
            byte[] bytes = file.getBytes();
            File dir = new File(Constants.HOME + "user_avatars/");

            File serverFile = new File(dir.getAbsolutePath() + File.separator + user_name + "."
                    + FilenameUtils.getExtension(name));
            try (BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile))) {
                stream.write(bytes);
            }
            user_avatar = "user_avatars/" + user_name + "." + FilenameUtils.getExtension(name);
        } catch (Exception e) {
            System.out.println("You failed to upload " + name + " => " + e.getMessage());
        }
    } else {
        System.out.println("You failed to upload " + name + " because the file was empty.");
    }
    Users.addUser(user_name, user_password, user_firstname, user_lastname, user_contacts, user_role,
            user_enabled, user_descr, user_avatar);
    return new ModelAndView("redirect:" + "/system/users");
}

From source file:ua.aits.Carpath.controller.SystemController.java

@RequestMapping(value = { "/system/user/do/updatedata.do",
        "/Carpath/system/user/do/updatedata.do" }, method = RequestMethod.POST)
public ModelAndView doEditUser(@RequestParam("user_avatar") MultipartFile file, HttpServletRequest request)
        throws SQLException, ClassNotFoundException, InstantiationException, IllegalAccessException,
        UnsupportedEncodingException {
    request.setCharacterEncoding("UTF-8");
    String user_id = request.getParameter("user_id");
    String user_name = request.getParameter("user_name");
    String user_password = request.getParameter("user_password");
    String user_role = request.getParameter("user_role");
    String user_enabled = request.getParameter("user_enabled");
    String user_firstname = request.getParameter("user_firstname");
    String user_lastname = request.getParameter("user_lastname");
    String user_descr = request.getParameter("user_descr");
    String user_contacts = request.getParameter("user_contacts");
    String name = file.getOriginalFilename();
    String user_avatar = request.getParameter("user_avatar_old");
    if (!file.isEmpty()) {
        try {//  w ww  .  j  a v a  2  s .  com
            byte[] bytes = file.getBytes();
            File dir = new File(Constants.HOME + "user_avatars/");

            File serverFile = new File(dir.getAbsolutePath() + File.separator + user_name + "."
                    + FilenameUtils.getExtension(name));
            try (BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile))) {
                stream.write(bytes);
            }

        } catch (Exception e) {
            System.out.println("You failed to upload " + name + " => " + e.getMessage());
        }
        user_avatar = "user_avatars/" + user_name + "." + FilenameUtils.getExtension(name);
    }
    if ("img/noavatar.png".equals(user_avatar)) {
        user_avatar = "";
    }
    Users.editUser(user_id, user_name, user_password, user_firstname, user_lastname, user_contacts, user_role,
            user_enabled, user_descr, user_avatar);
    return new ModelAndView("redirect:" + "/system/users");
}

From source file:uk.ac.abdn.fits.support.thymeleaf.springmail.web.MailController.java

@RequestMapping(value = "/sendMailWithAttachment", method = RequestMethod.POST)
public String sendMailWithAttachment(@RequestParam("recipientName") final String recipientName,
        @RequestParam("recipientEmail") final String recipientEmail,
        @RequestParam("attachment") final MultipartFile attachment, final Locale locale)
        throws MessagingException, IOException {

    this.emailService.sendMailWithAttachment(recipientName, recipientEmail, attachment.getOriginalFilename(),
            attachment.getBytes(), attachment.getContentType(), locale);
    return "redirect:sent.html";

}

From source file:uk.ac.abdn.fits.support.thymeleaf.springmail.web.MailController.java

@RequestMapping(value = "/sendMailWithInlineImage", method = RequestMethod.POST)
public String sendMailWithInline(@RequestParam("recipientName") final String recipientName,
        @RequestParam("recipientEmail") final String recipientEmail,
        @RequestParam("image") final MultipartFile image, final Locale locale)
        throws MessagingException, IOException {

    this.emailService.sendMailWithInline(recipientName, recipientEmail, image.getName(), image.getBytes(),
            image.getContentType(), locale);
    return "redirect:sent.html";

}

From source file:uk.ac.ebi.metabolights.controller.SubmissionQueueController.java

@RequestMapping(value = "/submitCompoundSpectra", method = RequestMethod.POST)
public ModelAndView uploadSpectra(@RequestParam("file") MultipartFile file,
        @RequestParam(required = true, value = "compoundid") String compound,
        @RequestParam(required = false, value = "owner") String owner, HttpServletRequest request)
        throws Exception {

    //Start the submission process...
    logger.info("Compound Reference Spectra Upload. Start");

    StringBuffer messageBody = new StringBuffer();
    String hostName = java.net.InetAddress.getLocalHost().getHostName();
    messageBody.append("Compound Reference Spectra submission started from machine " + hostName);

    // Get the user
    MetabolightsUser user = (MetabolightsUser) (SecurityContextHolder.getContext().getAuthentication()
            .getPrincipal());//from www. jav a  2 s  . co  m

    String submitter = user.getUserName();

    // If the user is a curator but there is an owner...
    if (owner != null && user.isCurator()) {

        // Overwrite the submitter with the owner...
        submitter = owner;
    }

    try {

        // Extend the message...
        messageBody.append("\nFileName: " + file.getOriginalFilename());
        messageBody.append("\nCompound Identifier: " + compound);

        if (submitter.equals(user.getUserName())) {
            messageBody.append("\nUser: " + user.getUserName());
        } else {
            messageBody.append("\nUser: " + user.getUserName() + "on behalf of " + submitter);
        }

        byte[] bytes = file.getBytes();

        File dir = new File(
                uploadSpectraDirectory + File.separator + user.getUserName() + File.separator + compound);
        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));
        stream.write(bytes);
        stream.close();

        logger.info("Server File Location=" + serverFile.getAbsolutePath());

        ModelAndView mav = AppContext.getMAVFactory().getFrontierMav("referencespectraupload");
        mav.addObject("compoundId", compound);
        mav.addObject("successfulUpload", "Compound Reference Spectra Uploaded Successfully");

        return mav;

    } catch (Exception e) {

        ModelAndView mav = AppContext.getMAVFactory().getFrontierMav("submitError");
        logger.error("Submission exception", e);
        mav.addObject("error", e);
        // Add the study id...
        mav.addObject("Compound ID", compound);
        messageBody.append("\n\nERROR!!!!!\n\n" + e.getMessage());
        return mav;
    }

}

From source file:vn.webapp.controller.cp.ExamController.java

/**
 * Save a room/*from  ww  w.j  a v a2  s  .com*/
        
 */
@RequestMapping(value = "saveExam", method = RequestMethod.POST)
public String saveExam(HttpServletRequest request,
        @Valid @ModelAttribute("examAdd") ExamValidation examValidation, BindingResult result, Map model,
        HttpSession session) {
    /*
     * Get list of paper category and journalList
     */

    /*
     * Put data back to view
     */

    if (result.hasErrors()) {
        return "cp.addExam";
    } else {
        /*
         * Prepare data for inserting DB
         */

        /**
         * Uploading file
         */
        MultipartFile sourceUploadFile = examValidation.getExamFileUpload();
        String fileName = sourceUploadFile.getOriginalFilename();
        String sourceUploadFileSrc = "";
        String StatusMessages = "";
        try {
            //Creating Date in java with today's date.
            Date currentDate = new Date();
            //change date into string yyyyMMdd format example "20110914"
            SimpleDateFormat dateformatyyyyMMdd = new SimpleDateFormat("HHmmssddMMyyyy");
            String sCurrentDate = dateformatyyyyMMdd.format(currentDate);

            byte[] bytes = sourceUploadFile.getBytes();
            String path = request.getServletContext().getRealPath("uploads");
            File dir = new File(path + "/exam");
            if (!dir.exists()) {
                dir.mkdirs();
            }

            // Create a file
            String currentUserName = session.getAttribute("currentUserName").toString();
            fileName = currentUserName + "_" + sCurrentDate + "_" + fileName;
            File serverFile = new File(dir.getAbsolutePath() + File.separator + fileName);
            if (serverFile.exists()) {
                sourceUploadFileSrc = dir.getAbsolutePath() + File.separator + fileName;
            }
            // Save data into file
            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
            stream.write(bytes);
            stream.close();
            List<ExamStatus> EXS_List = examStatusService.loadEXSList();
            boolean isToAdd = true;
            for (ExamStatus EXS : EXS_List) {
                if ((EXS.getEXS_AcaYear_Code().equals(examValidation.getAcademicYear()))
                        && (EXS.getEXS_Semester() == examValidation.getSemester())) {
                    isToAdd = false;
                    break;
                }
            }

            if (isToAdd)
                examStatusService.save(examValidation.getAcademicYear(), examValidation.getSemester(), 1);

            List<ExamInfo> examinfos = ReadExamInfos
                    .readFileExcel(dir.getAbsolutePath() + File.separator + fileName);
            int cnt = 0;
            try (DataOutputStream out = new DataOutputStream(
                    new FileOutputStream("examUploadStatus.bin", false))) {
                out.writeInt(examinfos.size());

                for (ExamInfo ei : examinfos) {
                    cnt++;
                    out.writeInt(cnt);
                    if (ei != null) {
                        String RCE_Code = examValidation.getAcademicYear() + "-" + examValidation.getSemester()
                                + "-" + ei.getClassCode() + "-" + ei.getGroup() + "-" + ei.getTurn() + "-"
                                + ei.getRoom();
                        Exam ex = examService.loadByCode(RCE_Code);
                        if (ex == null) {
                            examService.save(RCE_Code, examValidation.getAcademicYear(),
                                    examValidation.getSemester(), ei.getClassCode(), ei.getCourseCode(),
                                    ei.getCourseName(), Integer.parseInt(ei.getWeek()),
                                    Integer.parseInt(ei.getDay()), ei.getDate(), ei.getTurn(), ei.getSlots(),
                                    ei.getGroup(), ei.getRoom());
                        } else {
                            if (!((ex.getRCE_Date().equals(ei.getDate()))
                                    && (ex.getRCE_Day() == Integer.parseInt(ei.getDay()))
                                    && (ex.getRCE_Week() == Integer.parseInt(ei.getWeek()))
                                    && (ex.getRCE_Room_Code().equals(ei.getRoom())))) {
                                examService.edit(RCE_Code, examValidation.getAcademicYear(),
                                        examValidation.getSemester(), ei.getClassCode(), ei.getCourseCode(),
                                        ei.getCourseName(), Integer.parseInt(ei.getWeek()),
                                        Integer.parseInt(ei.getDay()), ei.getDate(), ei.getTurn(),
                                        ei.getSlots(), ei.getGroup(), ei.getRoom());
                                StatusMessages += "Cp nht thnh cng lp " + ex.getClass() + " nhm "
                                        + ex.getRCE_Group() + " thi\n";
                            }
                        }
                    }

                }
                StatusMessages += "Thm mi thnh cng " + cnt + " lp thi\n";
                model.put("status", StatusMessages);
                /**
                 * Preparing data for adding into DB
                 */

                //if(i_InsertAPaper > 0){
                //model.put("status", "Successfully saved a paper: ");
                //model.put("status",StatusMessages);
                System.out.println(StatusMessages);
                return "redirect:" + this.baseUrl + "/cp/Exams.html";
                //}
            } catch (Exception e) {
                model.put("status", "You failed to upload " + fileName + " => " + e.getMessage());
            }
        } catch (FileNotFoundException e) {
            System.out.println(e.getMessage());
        } catch (IOException e) {
            System.out.println(e.getMessage());
        } finally {
            try (DataOutputStream out = new DataOutputStream(
                    new FileOutputStream("examUploadStatus.bin", false))) {
            } catch (Exception e) {
            }
        }
        return "cp.addExam";
    }
}

From source file:vn.webapp.controller.cp.ExamController.java

@RequestMapping(value = "/OverlapExamListFromExcel", method = RequestMethod.POST)
public String overlapExamListFromExcel(HttpServletRequest request,
        @Valid @ModelAttribute("checkOverLapExam") FileValidation fileValidation, BindingResult result,
        Map model, HttpSession session) {
    /*/*from  www  .j  a  v  a 2s .  c  o  m*/
     * Get list of paper category and journalList
     */

    /*
     * Put data back to view
     */

    if (result.hasErrors()) {
        return "cp.checkOverLapExamFromExcel";
    } else {
        /*
         * Prepare data for inserting DB
         */

        /**
         * Uploading file
         */
        MultipartFile sourceUploadFile = fileValidation.getFileUpload();
        String fileName = sourceUploadFile.getOriginalFilename();
        String sourceUploadFileSrc = "";
        String StatusMessages = "";
        try {
            //Creating Date in java with today's date.
            Date currentDate = new Date();
            //change date into string yyyyMMdd format example "20110914"
            SimpleDateFormat dateformatyyyyMMdd = new SimpleDateFormat("HHmmssddMMyyyy");
            String sCurrentDate = dateformatyyyyMMdd.format(currentDate);

            byte[] bytes = sourceUploadFile.getBytes();
            String path = request.getServletContext().getRealPath("uploads");
            File dir = new File(path + "/exam");
            if (!dir.exists()) {
                dir.mkdirs();
            }

            // Create a file
            String currentUserName = session.getAttribute("currentUserName").toString();
            fileName = currentUserName + "_" + sCurrentDate + "_" + fileName;
            File serverFile = new File(dir.getAbsolutePath() + File.separator + fileName);
            if (serverFile.exists()) {
                sourceUploadFileSrc = dir.getAbsolutePath() + File.separator + fileName;
            }

            // Save data into file
            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
            stream.write(bytes);
            stream.close();

            HashMap<String, ArrayList<String>> m = ReadExamInfos
                    .Exam2TimeMapping(dir.getAbsolutePath() + File.separator + fileName);
            AcademicYear curAcadYear = academicYearService.getCurAcadYear();
            List<RegularCourseTimetableInterface> RCTTI_List = regularCourseTimetableInterfaceService
                    .loadRCTTIList(curAcadYear.getACAYEAR_Code());

            HashSet<String> exWeekSet = new HashSet<String>();
            for (String key : m.keySet()) {
                exWeekSet.add(key.split("_")[1]);
            }

            for (RegularCourseTimetableInterface rCTTI : RCTTI_List) {
                List<String> weeks = StringConvert.ExpandToListString(rCTTI.getWeek());
                int day = rCTTI.getDay();
                String room = rCTTI.getRoom();
                String[] slots = StringConvert.Expand(rCTTI.getSlot()).split(",");
                int startTurn = 0, endTurn = 0;
                try {
                    startTurn = (Integer.parseInt(slots[0]) - 1) / 3 + 1;
                    endTurn = (Integer.parseInt(slots[slots.length - 1]) - 1) / 3 + 1;
                } catch (NumberFormatException e) {
                    startTurn = endTurn = 0;
                }
                for (String exWeek : exWeekSet) {
                    if (weeks.contains(exWeek)) {
                        for (int i = startTurn; i <= endTurn; i++) {
                            String key = room + "_" + exWeek + "_" + day + "_Kp " + i;
                            if (m.containsKey(key)) {
                                ArrayList<String> val = m.get(key);
                                val.add("Lp h?c: " + rCTTI.getClasscode() + " " + rCTTI.getCoursecode()
                                        + " " + rCTTI.getCoursename());
                            }
                        }
                    }
                }
            }

            ArrayList<OverlapExam> overlapExamList = new ArrayList<OverlapExam>();
            ArrayList<String> val = new ArrayList<String>();

            for (String key : m.keySet()) {
                val = m.get(key);
                if (val.size() >= 2) {
                    int ok = 0;
                    String code = "";
                    for (String ex : m.get(key)) {
                        String[] tks = ex.split(" ");
                        if (code.equals(""))
                            code = tks[2];
                        else {
                            if (!code.equals(tks[2])) {
                                ok = 1;
                                break;
                            }
                        }
                    }
                    if (ok == 1) {
                        OverlapExam ovlE = new OverlapExam();
                        ovlE.setClassExamLst(val);
                        ovlE.setOverlapTime(key);
                        overlapExamList.add(ovlE);
                    }
                }
            }
            System.out.println("Done " + overlapExamList.size());
            model.put("status", StatusMessages);
            model.put("overlapExamList", overlapExamList);
            System.out.println(StatusMessages);
        } catch (Exception e) {
            model.put("status", "You failed to upload " + fileName + " => " + e.getMessage());
        }
        return "cp.overlapExamList";
    }
}

From source file:vn.webapp.controller.cp.RegularTimetableController.java

@RequestMapping(value = "/OverlapRoomList", method = RequestMethod.POST)
public String OverlapRoomList(HttpServletRequest request,
        @Valid @ModelAttribute("checkOverLapFromExcel") FileValidation fileValidation, BindingResult result,
        Map model, HttpSession session) {
    /*//from   w  w  w .  j a v a  2  s .  c  o m
     * Get list of paper category and journalList
     */
    List<AcademicYear> academicYearList = academicYearService.list();
    model.put("academicYearList", academicYearList);

    /*
     * Put data back to view
     */
    if (result.hasErrors()) {
        return "cp.checkOverlapRoomFromExcel";
    } else {
        /*
         * Prepare data for inserting DB
         */

        /**
         * Uploading file
         */
        MultipartFile sourceUploadFile = fileValidation.getFileUpload();
        String fileName = sourceUploadFile.getOriginalFilename();
        String sourceUploadFileSrc = "";
        try {
            //Creating Date in java with today's date.
            Date currentDate = new Date();
            //change date into string yyyyMMdd format example "20110914"
            SimpleDateFormat dateformatyyyyMMdd = new SimpleDateFormat("HHmmssddMMyyyy");
            String sCurrentDate = dateformatyyyyMMdd.format(currentDate);

            byte[] bytes = sourceUploadFile.getBytes();
            String path = request.getServletContext().getRealPath("uploads");
            File dir = new File(path + "/regularTimetables");
            if (!dir.exists()) {
                dir.mkdirs();
            }

            // Create a file
            String currentUserName = session.getAttribute("currentUserName").toString();
            fileName = currentUserName + "_" + sCurrentDate + "_" + fileName;
            File serverFile = new File(dir.getAbsolutePath() + File.separator + fileName);
            if (serverFile.exists()) {
                sourceUploadFileSrc = dir.getAbsolutePath() + File.separator + fileName;
            }
            // Save data into file
            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
            stream.write(bytes);
            stream.close();
            boolean isToAdd = true;
            ArrayList<OverlapRoom> overlapRooms = ReadTimeTableExcelFormat2
                    .CheckOverlap(dir.getAbsolutePath() + File.separator + fileName);
            System.out.println(overlapRooms);
            model.put("overlapRoomList", overlapRooms);
        } catch (Exception e) {
            e.printStackTrace();
            model.put("status", "You failed to upload " + fileName + " => " + e.getMessage());
        }

        return "cp.overlapRoomList";
    }
}

From source file:vn.webapp.controller.cp.RegularTimetableController.java

@RequestMapping(value = "/CheckSlotNumFromExcelFile", method = RequestMethod.POST)
public String checkSlotNumFromExcelFile(HttpServletRequest request,
        @Valid @ModelAttribute("checkSlotNumFromExcel") FileValidation fileValidation, BindingResult result,
        Map model, HttpSession session) {
    /*/*from   ww  w  .jav  a  2  s . co m*/
     * Get list of paper category and journalList
     */
    List<AcademicYear> academicYearList = academicYearService.list();
    model.put("academicYearList", academicYearList);

    /*
     * Put data back to view
     */
    if (result.hasErrors()) {
        return "cp.checkSlotNumFromExcel";
    } else {
        /*
         * Prepare data for inserting DB
         */

        /**
         * Uploading file
         */
        MultipartFile sourceUploadFile = fileValidation.getFileUpload();
        String fileName = sourceUploadFile.getOriginalFilename();
        String sourceUploadFileSrc = "";
        try {
            //Creating Date in java with today's date.
            Date currentDate = new Date();
            //change date into string yyyyMMdd format example "20110914"
            SimpleDateFormat dateformatyyyyMMdd = new SimpleDateFormat("HHmmssddMMyyyy");
            String sCurrentDate = dateformatyyyyMMdd.format(currentDate);

            byte[] bytes = sourceUploadFile.getBytes();
            String path = request.getServletContext().getRealPath("uploads");
            File dir = new File(path + "/regularTimetables");
            if (!dir.exists()) {
                dir.mkdirs();
            }

            // Create a file
            String currentUserName = session.getAttribute("currentUserName").toString();
            fileName = currentUserName + "_" + sCurrentDate + "_" + fileName;
            File serverFile = new File(dir.getAbsolutePath() + File.separator + fileName);
            if (serverFile.exists()) {
                sourceUploadFileSrc = dir.getAbsolutePath() + File.separator + fileName;
            }
            // Save data into file
            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
            stream.write(bytes);
            stream.close();
            boolean isToAdd = true;
            ReadTimeTableExcelFormat2 obj = new ReadTimeTableExcelFormat2();
            obj.readFileExcel(dir.getAbsolutePath() + File.separator + fileName);
            ArrayList<ClassRoomWrapper> invalidSlotNumList = obj.invalidSlotNumList;
            model.put("invalidSlotNumList", invalidSlotNumList);
            System.out.println(invalidSlotNumList.size());
        } catch (Exception e) {
            e.printStackTrace();
            model.put("status", "You failed to upload " + fileName + " => " + e.getMessage());
        }

        return "cp.invalidSlotNumList";
    }
}