1. 程式人生 > 其它 >ajax上傳檔案+傳json資料

ajax上傳檔案+傳json資料

請求後臺介面為需要檔案和JSON資料,例如請求如下:

  1. file: (binary)
  2. json: [{"faxNo":"02862075771","parent_id":"113","id":127,"spare1":"成都測試"}]
  3. goup: [{"goup_name":"成都測試"}]

前端程式碼:

var formData = new FormData()
var selectedFax = []
formData.append('file', files[0]);
var arr = [];
var goup_name = [];


$("#resource").treegrid("getCheckedNodes").map(function(item){
    var obj = {};
    obj.faxNo=item.faxNo;
    obj.parent_id=item.parent_id;
    obj.id=item.id;
    obj.spare1 = item.spare1;
    
    if(item.children){
        goup_name.push({goup_name:item.spare1});
    }
    arr.push(obj);
});
if(goup_name.length==0){
    arr.map(function(ite){
        goup_name.push({goup_name:ite.spare1});
    });
}
formData.append("json",JSON.stringify(arr));
formData.append("goup",JSON.stringify(goup_name));
$.ajax({
    url: '/xxxx/url/?phone=' + selectedFax.join(','),
    type: 'POST',
    data: formData,
    contentType: false,
    processData: false,
    success: function (res) {
        if (res.status == 200) {
            layer.msg('傳送成功')
            $('#fileModal').modal('hide')
        }
    },
    error: function () {
        layer.msg('傳送失敗');
        $("#otherSave").removeProp("disabled") ;
        $("#otherSave").prop("disabled",false);
        $("#otherSave").prop("disabled","");
        $("#otherSave").remove("disabled")
    },
})

後端程式碼:

@ApiOperation(value = "根據號碼和檔案傳送傳真-new")
@RequestMapping(value = "/sendFaxByFileAndPhoneNew",method = RequestMethod.POST)
public AjaxJsonView<Boolean>sendFaxByFileAndPhoneNew(@ApiParam(value = "pdf檔案",required = true)@RequestParam MultipartFile file,
                                                  @ApiParam(value 
= "phone(以英文逗號分隔)",required = true)@RequestParam String phone, @ApiParam(value = "json",required = false)@RequestParam String json, @ApiParam(value = "goup",required = false)@RequestParam String goup )
throws Exception{ System.out.println(file.getOriginalFilename()); }
時間,請帶我像一條小溪流般,安靜地流淌,匯入愛的海洋。