spring boot 下 ajax 上传文件

版权声明:本文为博主原创文章,未经博主允许不得转载。https://me.csdn.net/y18832550310

jsp:

点击上传

js:

/***
 * 附件上传
 * @param obj file-input对象
 */
function uploadfile(obj){
    var fjId_Obj=$(obj).attr("fjid");
    var formId_Obj=$(obj).attr("formid");
    var form = $("#"+formId_Obj)[0];
    var data = new FormData(form);
    var packageid=$("#"+fjId_Obj).val();
    $.ajax({
        url : "../newFiles/uploadFiles?packageid="+packageid,
        type : 'POST',
        enctype: 'multipart/form-data',
        data : data,
        processData: false,
        contentType: false,
        cache: false,
        timeout: 600000,
        success : function(data) {
            if(data.isok="true"){
                $("#"+fjId_Obj).val(data.data.packageid);
                console.log(data);
                selectFile(data.data.packageid,obj);
                callback_Function(obj);  //可重写
            }else{
                utils.wrans.show("提示",data.message,function(){
                    return false;
                });
            }
        },
        error: function (e) {
            utils.wrans.show("提示",e.message,function(){
                return false;
            });
        }
    });
};

controller:

/**
 * 上传
 */
@RequestMapping("/uploadFiles")
@ResponseBody
public Map uploadFiles(@RequestParam("files") MultipartFile[] uploadfiles, String packageid){
   MultiValueMap param= new LinkedMultiValueMap<>();
   try {
      for (int i = 0; i < uploadfiles.length; ++i) {
         byte[] bytes = uploadfiles[i].getBytes();
         MultipartFile uploadfile = uploadfiles[i];
         ByteArrayResource arrRe = new ByteArrayResource(bytes){
            /**
             * This implementation always returns {@code null},
             * assuming that this resource type does not have a filename.
             */
            @Override
            public String getFilename() {
               try {
                  return URLEncoder.encode(uploadfile.getOriginalFilename(),"UTF-8");
               } catch (UnsupportedEncodingException e) {
                  return null;
               }
            }
         };
         param.add("files",arrRe);
      }
      param.add("packageid",packageid);
      ;
      Map resultMap = newfileControllerFeign.uploadFiles(param);
      return resultMap;
   } catch (Exception e) {
      e.printStackTrace();
      logger.error("上传文件:",e);
      return null;
   }
}

 

你可能感兴趣的:(上传文件)