ajax上传文件并且判断是否为空

HTML

<div>
    
    <input type="file"  id = "file" >
    <button id="but">确定</button>
	
</div>

jquery

$("#but").click(function(){
    
  var format=new FormData();
  format.append("img",$('#file')[0].files[0]);//括号中第一个引号中写key第二个为值
 $.ajax({
     //几个参数需要注意一下
     type: "post",//方法类型
     url: "/addFile",//url
     data:format,
     dataType:"json",
     processData: false, // 告诉jQuery不要去处理发送的数据
     contentType: false, // 告诉jQuery不要去设置Content-Type请求头
     async:false,
     success: function (result) {
     console.log(result);//打印服务端返回的数据(调试用)
     if (0==result ) {
      alert("修改失败");

     }else{

      alert("修改成功");
       };
     },
     error : function() {
        alert("请稍后重试!");
       }
       })
});

java controller

/**
     * 添加文件
     * @param fileEntity
     * @return
     */
    @PostMapping("addFile")
    public int addFile(HttpServletRequest request, FileEntity fileEntity){

        return  operationService.addFile(request,fileEntity);
    }

java service

 //文件上传
        MultipartHttpServletRequest mr = (MultipartHttpServletRequest) request;
        if (null!=mr.getMultiFileMap().get("img")) {//判断是否有文件
            String systemPath = null;
            String path = "/upload/";
            try {
                systemPath = ResourceUtils.getURL("classpath:static").getPath().replace("%20", " ").replace('/', '\\').substring(1);//从路径字符串中取出工程路径
            } catch (Exception e) {
                e.printStackTrace();
            }
            String[] imgs = {"img"};
            String[] imgUrl = UploadFile.getFileURL(mr, imgs, systemPath, path);//上传文件公共方法
            fileEntity.setImgUrl(imgUrl[0]);
        }else{
            fileEntity.setImgUrl("");
        }

java  文件上传公共方法

 /**
     * 通过;spring 的方法解析所有方法
     * @param multipartRequest  请求
     * @param keys  获取参数key 对应的文件 key的值必须和前台页面的name值一样
     * @param systemPath    系统路径(活路径)
     * @param path  自己目录的路径
     * @return
     */
    public static String[]  getFileURL(MultipartHttpServletRequest multipartRequest, String[] keys, String systemPath, String path){
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        String[] vales=new String[keys.length];
        for (int i=0;i<keys.length;i++) {
            vales[i]=getPathValue(fileMap.get(keys[i]),systemPath,path);
        }
        return vales;
    }
    protected static String getPathValue(MultipartFile file,String systemPath,String path){
        if (!file.isEmpty()) {
            try {
                String fileName=file.getOriginalFilename();
                if(StringUtils.isNotBlank(fileName)){
                    String[] str=fileName.split("\\.");
                    if(str.length==1){
                        path=path+new Date().getTime()+str[0]+".JPEG";
                    }else{
                        path=path+new Date().getTime()+"."+str[str.length-1];
                    }

                }
                // 文件保存路径
                File fl=new File(systemPath+path);
                if(!fl.getParentFile().exists()){
                    fl.getParentFile().mkdirs();
                }
                // 转存文件
                file.transferTo(fl);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else{
            return null;
        }
        return  path;
    }

ps:如果有其他参数和文件一起上传,都需要放到format中

转载于:https://my.oschina.net/u/3535099/blog/3080966

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值