Js implements file upload

Js implements file upload

The js file upload is different from the form form upload. You can upload files without submitting the entire form. Therefore, I think

Html code

Backend springboot code

js code

   @RequestMapping("/upload")
    public JsonResoult<MyFile> uploadFile(@RequestParam("file") MultipartFile file,
                                          @RequestParam("contentid") String contentid,
                                          @RequestParam("contenttype") String contenttype){
        //在保存文件之前对文件做检查
        //判断文件是否为空
        if (file.isEmpty()){
            throw new IFileEmptyException("上传文件为空,上传失败");
        }

        //判断文件是否超过限制
        if (file.getSize() >Integer.valueOf(100000000) ){
            throw new IFileSizeException("文件过大,上传失败");
        }

        //判断上传的文件是否为图片类型 file.getContentType()获取的是这种形式 --> text/html
        if (!file.getContentType().contains(file.getContentType())){
            throw new IFileTypeNotMatchException("文件类型不符,上传失败");
        }

        //获取上传文件的原始名字
        String originalFilename = file.getOriginalFilename();

        //获取文件的后缀名
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));

        //使用时间戳为文件定义新的名字
        String uuidName = Timer.getTimeStamp().toString();

        //定义文件最终的名字
        String fileName = uuidName + suffix;

        //获取项目在服务器上的真实位置并拼凑文件最终的保存位置
        String realPath = System.getProperty("user.dir") + "/src/main/resources/static/upload/" + fileName;

        /**
         * 这里其实有两个选择:①直接将文件写入硬盘 这里选择这种
         * ②先获取存储文件的文件夹的路径,判断存储文件的文件夹是否存在,不存在则创建
         * 最后再将文件名和文件夹路径进行拼凑出最终文件的保存路径
         **/
        //虚拟创建目标文件
        File destFile = new File(realPath);

        //获取目标文件的上级目录
        File parentFile = destFile.getParentFile();

        if (!parentFile.exists()){
            //代表文件的上级目录不存在,进行创建
            parentFile.mkdirs();
        }

        //选择第一种方法,直接写入目标位置
        try {
            file.transferTo(destFile);
        }catch (IFileStatusException e) {
            throw new IFileStatusException("文件状态异常,写入失败");
        }catch (IOException e) {
            throw new IFileUploadIOException("服务器或数据库写入文件失败");
        }



        //将文件的下载路径写入数据库
        String fileAccessPath = "/upload/" + fileName;

        MyFile myFile = new MyFile();
        String id  = Timer.getTimeStamp().toString();

        myFile.setId(id);
        myFile.setStatus("1");
        myFile.setType(suffix.substring(1,suffix.length()));
        myFile.setUrl(fileAccessPath);
        myFile.setContentid(contentid);
        myFile.setContenttype(contenttype);
//        写入数据库
       if(myFileService.upLoadFile(myFile)){
           return new JsonResoult<MyFile>(ServerStatus.SUCCESS,"",myFile);
       }
        return new JsonResoult<MyFile>(ServerStatus.Fail);

    }

<!-- http://127.0.0.1:8080/file/upload -->
<script>
function submitForm() {
    var formData = new FormData();//必须是new FormData后台才能接收到
    formData.append("contentid","1")
    formData.append("contenttype","1")
    formData.append("file", $("#f1")[0].files[0]);
    $.ajax({
        url: "http://127.0.0.1:8080/file/upload",
        data: formData,
        type: 'post',
        datatype: "json",
        contentType: false,//必须false才会自动加上正确的Content-Type
        processData: false,//必须false才会避开jQuery对 formdata 的默认处理,XMLHttpRequest会对 formdata 进行正确的处理 
        success: function (jdata) {
            if(jdata.data.status == 200){
                alert("成功")
            }else{
                alert("失败")
            }
        }
    });
}
</script> 

<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

<div>
    <input type="text" id="t1" />
    <input type="file" id="f1" />
</div>

<input type="button" value="提交" onclick="submitForm()" />

Guess you like

Origin blog.csdn.net/qq_35889508/article/details/128178388