zoukankan      html  css  js  c++  java
  • java 文件上传

    一、前端页面

    1、html

     (1)设置input 的type类型为file,代表 用于文件上传。

     (2)accept属性,它规定能够通过文件上传进行提交的文件类型。accept值是 MIME 类型列表,多个类型之间用逗号隔开

    (3)multiple 属性是 HTML5 中的新属性。属性规定输入字段可选择多个值。多文件上传

    <div >
    <input id="addFile" class="form-control" class="filepath" type="file" multiple="multiple" accept="application/msword,application/vnd.ms-works,text/plain,application/pdf,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.wordprocessingml.document"><br>
    </div>
    2、js
    add: function () {
        var file = document.getElementById("addFile").files[0];
        if (file == null) {
            toastr.error('请上传文件');
            return false;
        }
        // 创建form对象
        var param = new FormData();
        // 通过append向form对象添加数据
        param.append('file', file);
        param.append('token', $('#token').val());
        // 上传需要将对应的文件类型上传的数据库
        param.append('fileType', fileType);
        $.ajax({
            cache: false,
            type: "POST",
            url: backbasePath + '/apia/v1/file/uploadFile',
            data: param,
            async: true,
            contentType: false,
            processData: false,
            success: function (data) {
                data = eval("(" + data + ")");
                if ('000000' == data.code) {
                    toastr.success(data.msg);
                    //上传成功之后清楚掉之前选择的文件
                    $("#addFile").val("");
                    // 上传成功之后进行table的重新加载
                    $('#filesList').DataTable().ajax.reload();
                } else if ('900000' == data.code) {
                    toastr.error('上传失败!');
                } else {
                    toastr.error(data.msg);
                }
                $("#upload").modal('hide');
            },
            error: function () {
                toastr.error('上传失败!');
                $("#upload").modal('hide');
            }
        });
    },
    二、后端代码
        // 上传文件
        @RequestMapping("/uploadFile")
        public Object upload(HttpServletRequest request, @RequestParam(required = false) MultipartFile file) {
            String result = null;if (null != file && !file.isEmpty()) {
                try {
                    // 检查文件大小
                    long fileSize = file.getSize();
                    if (fileSize > 1 * 1024 * 1024) {
                        return RequestResponseTool.getJsonMessage(RespCode.repeat, "上传失败!上传的文件大小超出了1M限制!");
                    }
                    // 检查文件MIME类型
                    String contentType = file.getContentType();
                    List<String> types = new ArrayList<String>();
                    //扩展名 doc dot
                    types.add("application/msword");
                    //扩展名 docx
                    types.add("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
                    //扩展名 pdf
                    types.add("application/pdf");
                    //扩展名 txt
                    types.add("text/plain");
                    //扩展名 wps
                    types.add("application/vnd.ms-works");
                    //扩展名 xla xlc xlm xls xlt xlw
                    types.add("application/vnd.ms-excel");
                    if (!types.contains(contentType)) {
                        return RequestResponseTool.getJsonMessage(RespCode.repeat, "上传失败!不允许上传此类型的文件!");
                    }
                    // 获取原始文件名
                    String originalFilename = file.getOriginalFilename();
                    String path = filePath;
                    path = path + "/upload/";//定义位绝对路径
                    File parent = new File(new File(path).getAbsolutePath());
                    System.out.println("	parent=" + parent);
                    if (!parent.exists()) {
                        parent.mkdirs();
                    }
                    Date date = new Date();
                    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                    Map<String, Object> m = new HashMap<String, Object>();
                    // 根据文件名称进行查询,如果存在则更新否则新增
                    Map<String, Object>  fileMap = knowledgeService.getFileByName(originalFilename);
                    // 如果能查询出对应的数据,则进行更新操作
                    if(fileMap !=null && fileMap.size() >0){
                        String id =fileMap.get("id").toString();
                        String oldfileName =fileMap.get("file_name").toString();
                        // 找到之前的文件,如果存在则删除
                        File oldFile = new File( path+"/"+oldfileName);
                        if (oldFile.exists()) {
                            oldFile.delete();
                        }
                        // 保存当前的文件
                        file.transferTo(new File(parent, oldfileName));
                        // 更新文件表中的大小
                        m.put("id", id);
                        m.put("file_size", fileSize);
                        result = knowledgeService.update(m);
                    }
                    // 如果查不到数据,则进行新增操作
                    else {
                        // 新文件名称
                        String filename = UUID.randomUUID().toString();
                        String suffix = "";
                        int beginIndex = originalFilename.lastIndexOf(".");
                        if (beginIndex != -1) {
                            suffix = originalFilename.substring(beginIndex);
                        }
                        // 执行保存文件
                        file.transferTo(new File(parent, filename + suffix));
                        // 存放的文件路径
                        String file_path = "/upload/" + filename + suffix;
                        //id
                        String knowledgeId = IDCode.knowledgeId + IDTool.getWebUserId() + "";
                        //文件表Id
                        String file_id = IDCode.fileId + IDTool.getWebUserId() + "";
                        //文件逻辑名称(和路径中的名称保持一致)
                        String file_name = filename + suffix;
                        //  知识资源表中的主键
                        m.put("id", knowledgeId);// 文件id
                        m.put("file_id", file_id);// 创建时间
                        m.put("create_time", dateFormat.format(date));
                        m.put("file_name", file_name);
                        m.put("file_real_name", originalFilename);
                        m.put("file_path", file_path);
                        m.put("file_size", fileSize);
                // 执行新增操作 result
    = knowledgeService.add(m); } return result; } catch (Exception ex) { ex.printStackTrace(); } } return result; }


  • 相关阅读:
    取某个关键词以及之后的数据
    从SQL下载大量数据到Excel
    SQL 分页
    whereis linux文件搜索
    crontab Linux定时器工具
    Angular
    工具
    百度OAuth2.0登录
    JS事件学习 拖拽,鼠标键盘事件实例汇总
    信息栏滚动效果学习总结
  • 原文地址:https://www.cnblogs.com/flyShare/p/12498064.html
Copyright © 2011-2022 走看看