package com.weavi.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

@Controller

public class FileUploadController {
    @RequestMapping("/")
    public String fileupload(){
        return "upload";
    }

    @RequestMapping("/upload")
    public String upload(HttpServletRequest request, @RequestParam("file") MultipartFile file) throws IOException {

        if(!(file.isEmpty())){
            String path = request.getServletContext().getRealPath("/upload");
            System.out.println("path: "+path);
            String fileName = file.getName();
            System.out.println("file Name: "+fileName);
            String filename = file.getOriginalFilename();
            File filePath = new File(path,fileName);
            if(!(filePath.getParentFile().exists())){
                filePath.getParentFile().mkdirs();
            }
            file.transferTo(new File(path+File.separator+filename));
            return "success";
        }else
            return "error";
    }
}
