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("\tparent=" + 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; }

 




免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM