如何使用Ajax将嵌套的json对象发送到控制器

时间:2019-05-04 13:17:50

标签: json hibernate spring-boot spring-mvc spring-data-jpa

我想做的是将嵌套的json对象传递给控制器 从那里我必须分别设置这些实体的字段。我有两个名为UserData和Address的实体,我想根据项目需要为这两个实体获取嵌套对象。

您可以在此阶段看到,我不知道如何解决此问题。帮我解决这个问题。

/ 前端 /

<body>

    <div class="container">
        <div class="jumbotron">
            <h1>File upload Demo</h1>
            <p>File upload Demo along with the JSON data</p>
        </div>

    </div>

    <div class="container">

        <div class="alert alert-success">File uploaded successfully</div>

        <div class="alert alert-danger">File is not uploaded. Error occurred</div>

        <div class="form-group">
            <label for="firstname">First Name:</label> <input type="text"
                class="form-control" id="firstname" name="firstname">
        </div>

        <div class="form-group">
            <label for="lastname">Last Name:</label> <input type="text"
                class="form-control" id="lastname" name="lastname">
        </div>
        <div class="form-group">
            <label for="state">State:</label> <input type="text"
                class="form-control" id="state" name="state">
        </div>
        <div class="form-group">
            <label for="city">City:</label> <input type="text"
                class="form-control" id="city" name="city">
        </div>

        <form id="fileUploadForm">
            <div class="form-group">
                <input type="file" class="form-control-file border" name="file">
            </div>
        </form>

        <button type="button" id="btnSubmit" class="btn btn-primary">Submit</button>

    </div>

    <script>
$(document).ready(function () {
    $(".alert-success").hide();
    $(".alert-danger").hide();

    $("#btnSubmit").click(function () {
     alert("hello");

    var form = $('#fileUploadForm')[0];
        var data = new FormData(form);



        var jsonDataObj = {
            "firstname": $("#firstname").val(),
            "lastname" : $("#lastname").val(),

            "address"  :{
                "state": $("#state").val(),
                "city" : $("#city").val()
            }
        };
        data.append("jsondata", JSON.stringify(jsonDataObj));
        $("#btnSubmit").prop("disabled", true);
        $.ajax({
            type: "POST",
            enctype: 'multipart/form-data',
            url: "/upload",
            data: data,
            processData: false,
            contentType: false,
            cache: false,
            timeout: 600000,
            success: function (data) {

                console.log("SUCCESS : ", data);
                $("#btnSubmit").prop("disabled", false);
                $(".alert-success").show();
                $(".alert-danger").hide();

            },
            error: function (e) {
                 $(".alert-success").hide();
                 $(".alert-danger").show();
                console.log("ERROR : ", e);
                $("#btnSubmit").prop("disabled", false);
            }
        });
    });
});
</script>

    </body>




/**controller**/

@Controller
public class FileUploadRestController {

    @Autowired UserRepo userRepo;
    @Autowired uploadrep upld;
    ObjectMapper objectMapper = new ObjectMapper();
    ObjectMapper addressmap = new ObjectMapper();

    @RequestMapping(value="/upload", method=RequestMethod.POST)
    public ResponseEntity<Object> uploadFile(@RequestParam(required=true, value="file") MultipartFile file, @RequestParam(required=true, value="jsondata")String jsondata) throws IOException, ParseException  {
        System.out.println("file name is "+file.getOriginalFilename());
        JSONParser parser = new JSONParser();
        JSONObject json = (JSONObject) parser.parse(jsondata);
        //System.out.println(json.getString("firstname"));
        /*File convertFile = new File("c://mydownloads//"+file.getOriginalFilename());
        convertFile.createNewFile();
        FileOutputStream fout = new FileOutputStream(convertFile);
        fout.write(file.getBytes());
        fout.close();*/
        System.out.println("data ies "+json);
        //UserData personData = objectMapper.readValue(jsondata, UserData.class);
        //Address addressData = addressmap.readValue(jsondata, Address.class);
        //Address address =new Address(addressData.getState(),addressData.getCity());
        /*UserData userData=new UserData(StringUtils.cleanPath(file.getOriginalFilename()),file.getContentType(),file.getBytes(),personData.getFirstname(),personData.getLastname());

        System.out.println("uploaded datafiles ");
        //String str=Base64.getEncoder().encodeToString(file.getBytes());

        userData.setAddress(address);

        userRepo.save(userData);*/
        return new ResponseEntity<>("File is uploaded successfully", HttpStatus.OK);

    }

0 个答案:

没有答案