1. 程式人生 > >上傳檔案儲存本地

上傳檔案儲存本地

<%@ page language="java" pageEncoding="UTF-8"%>
<!DOCTYPE HTML>
<html>
<head>
    <title>檔案上傳</title>
    <script src="/resources/js/jquery-3.3.1.js"></script>
</head>

<body>
<%--<form action="#" enctype="multipart/form-data" method="post">--%>
<form>
    上傳使用者:<input type="text" name="username"><br/>
    上傳檔案:<input type="file" name="file" id="file"><br/>
    <img id="show-img" width="200px" height="200px"/>
    <input name="driverLicenceImg" id="img" hidden/>
    <input type="submit" id ="submit" value="提交">
</form>
<script>
    $("#file").on("change", function () {
        var fileObj = this.files[0];
        var formFile = new FormData();
        formFile.append("file", fileObj);
        var data = formFile;
        $.ajax({
            url: "/upload",
            type: "post",
            data: data,
            dataType: "json",
            processData: false,
            contentType: false,
            success: function(data) {
                $("#img").attr("value", data.url);;
                $("#show-img").attr("src", data.url);
            },
            error: function() {
            }
        });
    });
</script>
</body>
</html>

@Controller
public class UploadController {
//tomcat配置虛擬地址自行百度,so easy
    private static String VIRTUAL_PATH = "http://localhost:8080/imgs";
    private static String PHYSICAL_PATH = "e://test/imgs";
    @RequestMapping(path = "/upload", method = RequestMethod.POST)
    @ResponseBody
    public Object upload(MultipartFile file) {
//        String rootPath = Thread.currentThread().getContextClassLoader().getResource("/").getPath();
        String rootPath = PHYSICAL_PATH;
        String datePath = getAbsolutePathDate(rootPath);
        try {
            File localFile = new File(datePath + "/" + file.getOriginalFilename());
            localFile.createNewFile();
            file.transferTo(localFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        Map<String,Object> map = new HashMap<>();
        map.put("url",getAbsolutePathDate(VIRTUAL_PATH)  + "/" + file.getOriginalFilename());
        return map;
    }
    private String getAbsolutePathDate(String rootPath){
        DateFormat df = new SimpleDateFormat("yyyyMMdd");
        String ds = df.format(new Date());
        String path = rootPath+"/"+ ds;
        File folder = new File(path);
        if(!folder.exists()){
            folder.mkdirs();
        }
        return path;
    }

}