FormData传递数据

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<input type="text" name="username" id="t1" value="123">
<input type="text" name="password" id="t2">
<input type="file" name="myfile" id="t3">
<button id="button" onclick="upload()">提交</button>

<script>
    function upload() {
        var formData = new FormData();
        formData.append("username",$("#t1").val())
        formData.append("password",$("#t2").val())
        formData.append("file",$("#t3")[0].files[0])

        $.ajax({
            url:'http://localhost:8081/upload',
            method:'post',
            data:formData,
            contentType:false,// 不用任何编码
            processData:false, //告诉浏览器不要处理我的数据,直接发送
            success:function(data){
                console.log(data)
            }
        })
        console.log(formData);
    }

</script>

</body>
</html>
@RestController
public class FileUploadController {
    SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");

    @PostMapping("/upload")
    @CrossOrigin
    public String upload(MultipartFile file, HttpServletRequest req,String username,String password){
        System.out.println("username = " + username);
        System.out.println("password = " + password);
        ServletContext servletContext = req.getServletContext();
        String format = sdf.format(new Date());
        String realPath = servletContext.getRealPath("/img")+format;
        System.out.println("realPath = " + realPath);
        File folder = new File(realPath);
        if(!folder.exists()){
            folder.mkdirs();
        }
        String oldName = file.getOriginalFilename();
        String newName = UUID.randomUUID().toString().replace("-","") + oldName.substring(oldName.lastIndexOf("."));

        try {
            file.transferTo(new File(folder,newName));
            return req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + "/img" + format + newName;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "error";
    }
}
上一篇:GoLang设计模式05 - 原型模式


下一篇:python 批量创建文件夹