com.kalai.controller.FileUploadController.java Source code

Java tutorial

Introduction

Here is the source code for com.kalai.controller.FileUploadController.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.kalai.controller;

import com.kalai.filesupload;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

/**
 *
 * @author kalaiselvan.a
 */
@Controller
public class FileUploadController {

    @RequestMapping(value = "/fileupload", method = RequestMethod.GET)
    public String fileupload(ModelMap map) {
        map.addAttribute("uploadoption", "singlefile");
        //map.addAttribute("uploadoption","upload");
        return "fileupload";
    }

    @RequestMapping(value = "/fileupload", method = RequestMethod.POST)
    public @ResponseBody String fileuploadstore(@RequestParam("name") String name,
            @RequestParam("file") MultipartFile file, ModelMap map) {
        if (!file.isEmpty()) {
            try {
                byte[] bytes = file.getBytes();
                BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(name)));
                stream.write(bytes);
                stream.close();
                map.addAttribute("uploadoption", "uploaded");
                map.addAttribute("Status", "uploaded Successfully" + name);

            } catch (Exception e) {
                map.addAttribute("uploadoption", "uploaded");
                map.addAttribute("Status", "uploaded UnSuccessfully" + name);
            }
        } else {
            map.addAttribute("Status", "uploaded  is Empty" + name);
        }
        return "fileupload";
    }

    @RequestMapping(value = "/savefiles", method = RequestMethod.POST)
    public String fileupload(@ModelAttribute("uploadForm") filesupload fileup, Model map)
            throws IllegalStateException, IOException {
        String saveDirectory = "D:/spring_file_upload/";
        List<MultipartFile> files = fileup.getFiles();
        List<String> filenames = new ArrayList<String>();
        try {
            if (null != files && !files.isEmpty()) {
                for (MultipartFile multipartfile : files) {
                    String fileName = multipartfile.getOriginalFilename();
                    if (!"".equalsIgnoreCase(fileName)) {
                        multipartfile.transferTo(new File(saveDirectory + fileName));
                        filenames.add(fileName);
                    }
                }
                map.addAttribute("uploadoption", "uploaded");
                map.addAttribute("files", filenames);
            } else {
                map.addAttribute("uploadoption", "emptyfiles");
                map.addAttribute("files", filenames);
            }

        } catch (Exception e) {
            return e.getMessage();
        }
        return "fileupload";
    }

    @RequestMapping(value = "uploadMultipleFiles", method = RequestMethod.POST)
    public @ResponseBody String handleFileUpload(@RequestParam("files") MultipartFile files[]) {
        try {
            String filepath = "D:/spring_file_upload/";
            StringBuffer result = new StringBuffer();
            byte[] bytes = null;
            result.append("Uploading of files(s)");
            for (int i = 0; i < files.length; i++) {
                if (!files[i].isEmpty()) {
                    bytes = files[i].getBytes();
                    BufferedOutputStream stream = new BufferedOutputStream(
                            new FileOutputStream(new File(filepath + files[i].getOriginalFilename())));
                    stream.write(bytes);
                    stream.close();
                    result.append(files[i].getOriginalFilename() + "OK.");
                } else {
                    result.append(files[i].getOriginalFilename() + "Failed.");
                }
            }
            return result.toString();
        } catch (Exception e) {
            return e.getMessage();

        }
    }

    @RequestMapping(value = "/uploadMultiple", method = RequestMethod.POST)
    public String handlefile(ModelMap map, filesupload file) {
        String returnval = "", sRootPath = "", fileName = "", ext = "", newname = "";
        byte[] bytes = null;
        String filepath = "D:/spring_file_upload/";
        long filesize = 0;
        try {
            filesize = file.getFile().getSize();
            fileName = file.getFile().getOriginalFilename();
            ext = fileName.substring(fileName.lastIndexOf("."));
            newname = "Hai-New-File" + System.currentTimeMillis();

            // map.addAttribute("Status", "file has error");
            if (file.getFile().isEmpty()) {
                map.addAttribute("Status", "file has error");
                map.addAttribute("uploadoption", "singlefile");
            } else {
                bytes = file.getFile().getBytes();
                //BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(newname)));
                FileOutputStream out = new FileOutputStream(filepath + file.getFile() + newname + ext);
                out.write(bytes);
                //stream.write(bytes);
                //stream.close();

                out.close();
                map.addAttribute("Status", "fileuploaded---" + newname);
                map.addAttribute("uploadoption", "singlefile");
            }

            return "fileupload";
        } catch (Exception e) {
            return "PageNotFound";
        }
    }

}