• HTML5使用Ajax上传文件


    HTML5页面

    1. <form id="uploadForm" enctype="multipart/form-data">
    2. <input id="file" type="file" name="file" multiple="multiple" onchange="selectFile()"/><br>
    3. form>

    JS

    //引入jquery
    
    

    项目需要阿里巴巴的fastjson以便返回json数据

    pom.xml

    
       com.alibaba
       fastjson
       1.2.59
    

    后台代码

    保存路径是

    项目文件\target\classes\static\images\temp

    @PostMapping("upload")
    @ResponseBody
    public JSONObject upload(@RequestParam("file") MultipartFile file){
        JSONObject josn=new JSONObject();
        try {
            String pathA= ResourceUtils.getURL("classpath:").getPath()+"static";
            String detail_path="/images/temp/";
             
        if (file.isEmpty()){
            josn.put("code","error");
            josn.put("message","未选择文件");
            return josn;
        }
        File fileA=new File(pathA); 
        if(!fileA.exists){
             fileA.mkdirs();
       } 
        String filename = file.getOriginalFilename(); //获取上传文件原来的名称
        String filePath = pathA+detail_path;
        System.out.println(filePath);
        File temp = new File(filePath);
        if (!temp.exists()){
            temp.mkdirs();
        }
    
            File localFile = new File(filePath+filename);
            file.transferTo(localFile); //把上传的文件保存至本地
            System.out.println(file.getOriginalFilename()+" 上传成功");
            josn.put("code","sucess");
            //返回文件上传后的目录
            josn.put("message",detail_path+filename);
            return josn;
        }catch (IOException e){
            e.printStackTrace();
            josn.put("code","error");
            josn.put("message","文件上传失败,原因是:"+e.getMessage());
            return josn;
        }
    }
  • 相关阅读:
    微信小程序开发SSM投票系统+后台管理系统|前后分离VUE
    STM32WL开发之易智联LORA评估板上按键KEY的配置与应用
    Mysql-库的操作
    “蔚来杯“2022牛客暑期多校训练营4 L.Black Hole 垃圾计算几何
    八位阿里p8耗时十年总结出Java面试复盘手册,带你实现逆风翻盘
    云原生 CI/CD 平台架构设计
    甲方需求被公司明确指示不能做,身为公司项目经理,怎么处理?
    notepad++编辑多个位置
    sed 原地替换文件时遇到的趣事
    GORM CRUD 5 分钟快速上手
  • 原文地址:https://blog.csdn.net/weixin_44710155/article/details/126103491