如何在春季启动时使用Ajax发布包含json格式的文件和数据的表单

时间:2018-07-08 07:16:57

标签: ajax spring spring-boot

我是Spring Boot的新手,我想发布一个包含数据和文件的表格 (pojo类属性)我想将json格式的表单发送给控制器,我该如何在Spring Boot应用程序中使用Ajax做到这一点。 当我提交表单时,控制器会引发以下错误。 java.lang.IllegalStateException:当前请求的类型不是[org.springframework.web.multipart.MultipartHttpServletRequest]:ServletWebRequest:uri = / item / uploadItem; client = 0:0:0:0:0:0:0:1 ; session = 8E478D7285FE567A40F6DEAEEC9F29B6

  

这是我的pojo课

@Id
    @GenericGenerator(name="incrementer",strategy="increment")
    @GeneratedValue(generator="incrementer")
    private long id;
    private String title;
    private String brand;
    private String model;
    private double price;
    private String condation;
    @DateTimeFormat(pattern="yyyy-MM-dd")
    private Date uploadDate;
    private long ownerId;
    private long visiters;
    private String description;
    private long paymentId;
    private int priority;
    private String province;
    private String kmDriven;
    private String catagorey;
    private String subCatagorey;
    private String fuel;
    private String madeOfCountry;
    private String insuranceExpireDate;
    private String color;
    private String priceMonetaryUnit;
    private String gender;
    private String itemAvailableAddress;
    private String zone;
    @OneToMany
    @JoinColumn(name="itemId")
    private List<ImageDTO> image;
    private List<MultipartFile> imageFromUser;
  

这是控制器方法

@PostMapping(value="/uploadItem",consumes=MediaType.APPLICATION_JSON_VALUE,produces=MediaType.APPLICATION_JSON_VALUE)
public Response saveItem(HttpServletRequest requist,@RequestBody ItemDTO itemDTO) {
    System.out.println("save method of upload image");

    itemService.saveItem(itemDTO);
    return new Response("Item uploaded successfully");
}
  

Ajax代码

$( document ).ready(function() {
    $("#uploadVehical").submit(function(event){
        event.preventDefault();
        uploadItem();
    });

    // UPLOADING ITEM FROM 
    function uploadItem(){

        var itemData = {
                title : $("#title").val(),
                brand: $("#brand").val(),
                model : $("#model").val(),
                catagorey : $("#catagorey").val(),
                subCatagorey : $("#subCatagorey").val(),
                itemAvailableAddress : $("#itemAvailableAdddress").val(),
                condation : $("#vehicalState").val(),
                price : $("#vehicalPrice").val(),
                province : $("#ownerProvince").val(),
                ownerPhoneNumber : $("#ownerContactno").val(),
                description :$("#description").val(),
                fuel : $("#vehicalUsingFuel").val(),
                kmDriven : $("#kmDriven").val(),
                madeOfCountry : $("#madeOfCountry").val(),
                insuranceExpireDate : $("#insuranceExpireDate").val(),
                priceMonetaryUnit : $("#monetaryUnit").val(),
                color : $("#vehicalColor").val(),
                imageFromUser : $("#image").val()
                }
        $.ajax({
            type : "POST",
            contentType : "application/json",
            url :  "/item/uploadItem",
            data : JSON.stringify(itemData),
            dataType : 'json',
            success : function(result) {
                if(result.message !=null){
                alert(result.message);
                //window.location.href = "/burkaFarkhar/mainPage1";
                }

            },
            error : function(e) {
                alert("Error! please enter proper data"),
                console.log();
            }
        });
    }
})
  

html表单

<form id="uploadVehical" enctype="multipart/form-data">
title:<input type="text" id="title" name="title">
catagorey<select id="catagorey" name="catagorey">
<option>motor</option>
<option>truck</option>
<option>container</option>
<option>bus</option>
</select>
sub catagorey <select id="subCatagorey" name="subCatagorey" >
<option value="1">1</option >
<option value="2">2</option>
<option value="3">3</option>
</select>
brand:<select id="brand" name="brand">
<option>corolla</option>
<option>toyota</option>
<option>dogsun</option>
<option>surf</option>
</select>
made of country:<select id="madeOfCountry" name="madeOfCountry">
<option>Germany</option>
<option>Rusian</option>
<option>Jupan</option>
<option>India</option>
</select>
year model:<input type="text" id="model" name="model">
Price:<input type="number" id="vehicalPrice" name="price">
Monetary Unit:<select id="monetaryUnit" name="insuranceExpireDate">
<option value="afghany">Aghany</option>
<option value="dollar">Dollar</option>
</select>
Fuel:<select id="vehicalUsingFuel" name="fuel">
<option value="petrol">Petrol</option>
<option value="diesel">Petrol</option>
<option value="gas">gas</option>
<option value="electronic">electronic</option>
</select>
vehical State:<select id="vehicalState" name="condation">
<option value="new">New</option>
<option value="working">working</option>    
<option value="used">used</option>
<option value="notworking">Not working</option>             
</select>
KM Driven:<input type="text" id="kmDriven" name="kmDriven">
Vehical Color:<input type="text" id="vehicalColor" name="color">
InsuranceExpireDate:<input type="text" id="insuranceExpireDate" name="insuranceExpireDate">
First photo:<input type="file" id="image" name="imageFromUser">

Description:<textarea rows="5" cols="20" name="description" id="description"></textarea>
<br>
<h2>Owner related details</h2> 

Item available address:<input type="text" name="itemAvailableAddress" id="itemAvailableAdddress">
<input type="submit" value="Submit">
</form> 

2 个答案:

答案 0 :(得分:0)

html部分

<form id="data" method="post" enctype="multipart/form-data">
    <input type="text" name="first" value="Bob" />
    <input type="text" name="middle" value="James" />
    <input type="text" name="last" value="Smith" />
    <input name="image" type="file" />
    <button>Submit</button>
</form>

ajax part

$("form#data").submit(function(e) {
    e.preventDefault();    
    var formData = new FormData(this);

    $.ajax({
        url: window.location.pathname,
        type: 'POST',
        data: formData,
        success: function (data) {
            alert(data)
        },
        cache: false,
        contentType: false,
        processData: false
    });
});

Spring mvc控制器

//为患者上传处方图像

@RequestMapping(value="/url" ,method = RequestMethod.POST, headers = "Accept=application/json")
    public ResponseEntity<String> updateFromJson(HttpServletRequest request, HttpServletResponse response) {
        byte[] imageBytes = null; 
        try{
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            String uniqueId =multipartRequest.getParameter("uniqueId").trim();

            for(Entry<String, MultipartFile> entry : multipartRequest.getFileMap().entrySet()) {
                System.out.println(entry.getKey());
                System.out.println(entry.getValue().getBytes());
                System.out.println(entry.getValue().getOriginalFilename());

                if(null != entry.getKey()){
                    imageBytes = entry.getValue().getBytes();//this is the image file
                }
            }

            //write code for save the image and send response to ajax

        }catch(Exception ex){
            ex.printStackTrace();
        }
    }

注意:在上面的示例中,为了向您展示我正在发送一个参数以及一个文件。请根据您的需要修改代码。

答案 1 :(得分:0)

  

我通过使用以下ajax代码解决了这个问题

ipconfig