java关于文件上传的万能版本

前端页面:

<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8" %>
<%@ include file="/WEB-INF/layouts/base.jsp" %>
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body class="konwledge-add-body">
<div class="konwledge-add">

    </div>
    <div class="form-group">
        <label for="uploadFile" class="col-xs-3 control-label">添加附件:</label>
        <div class="col-xs-9">
            <button type="button" class="btn default upload-btn">
                选择文件
                <input type="file" class="ui-outsourcing-form-upload" id="uploadFile"
                    onchange="uploadFlowFile()"/>
            </button>
            <div id="flowFileNames">

            </div>
        </div>
    </div>
</div>
<script src="${ctxstaadmin}/plugins/jquery/jquery-1.12.4.js"></script>
<script>
    function uploadFlowFile() {
     
        var url = "${ctx}/file/addfile";
        var formData = new FormData();
        var fileName = document.getElementById("uploadFile").files[0].name;
        if (learningFileList.length > 0) {
     
            for (let i = 0; i < learningFileList.length; i++) {
     
                var map = jsonToMap(learningFileList[i]);
                if (map.get('name') == fileName) {
     
                    layer.msg('文件' + fileName + '已经上传,请勿重复上传文件!', {
     time: 3000});
                    return;
                }
            }
        }
        formData.append("file", document.getElementById("uploadFile").files[0]); //加入文件对象
        $.ajax({
     
            type: "POST",
            url: url,
            data: formData,
            cache: false,//上传文件无需缓存
            processData: false,//用于对data参数进行序列化处理 这里必须false
            contentType: false, //
            success: function (R) {
     
                if (R.code == 0) {
     
                    layer.msg('上传成功', {
     
                        time: 1500
                    }, function () {
     
                     
                    });
                }else {
     
                    layer.msg(R.msg, {
     
                        icon: 2,
                        time: 2000
                    });
                }
            }
        });
    }

</script>
</body>
</html>

后端控制层代码:

package com.jszh.knowledge.os.controller.file;

import com.jszh.common.util.DateUtils;
import com.jszh.common.util.R;
import com.jszh.knowledge.os.base.OSBaseController;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.ResourceBundle;

/**
 * 

* 前端控制器 *

* * @author ${author} * @since 2020-07-29 */
@Controller @RequestMapping("file") public class FileController extends OSBaseController { /** * 提交BPO文件 * @param * @return */ @PostMapping("/addfile") @ResponseBody public R addfile(@RequestParam(value = "file") MultipartFile file){ if(StringUtils.isBlank(file.getOriginalFilename())){ return R.error(-1, "请上传文件"); } System.out.println(file.getOriginalFilename()); String mulu = DateUtils.format(new Date(), "yyyyMMdd") + "/"; String path = ResourceBundle.getBundle("config/filePath").getString("learningfilepath")+mulu;//需要上传到的文件夹路径 String Downpath = ResourceBundle.getBundle("config/filePath").getString("Downlearningfilepath")+mulu;//需要存数据库的文件路径 String Filename = System.currentTimeMillis()+file.getOriginalFilename();//文件名 String filepath = "";//文件的储存路径 long filesize = file.getSize(); System.out.println("文件大小:"+filesize); if(filesize>10485760){ return R.error("文件过大超出限制,请上传10M以内的文件!"); } String fileName = file.getOriginalFilename(); String[] strArray = fileName.split("\\."); int suffixIndex = strArray.length -1; String fileType = strArray[suffixIndex]; if(fileType.equalsIgnoreCase("txt")||fileType.equalsIgnoreCase("doc")||fileType.equalsIgnoreCase("docx")||fileType.equalsIgnoreCase("DOC")||fileType.equalsIgnoreCase("DOCX")||fileType.equalsIgnoreCase("xlsx")||fileType.equalsIgnoreCase("xls")||fileType.equalsIgnoreCase("zip")||fileType.equalsIgnoreCase("rar")||fileType.equalsIgnoreCase("7z")||fileType.equalsIgnoreCase("pdf")){ }else{ return R.error(500,"请上传正确格式的文档"); } try { InputStream in = file.getInputStream(); byte[] buffer = new byte[1024]; int len = 0; File file1 = new File(path+Filename); File fileParent = file1.getParentFile(); if (!fileParent.exists()) { fileParent.mkdirs(); } OutputStream out = new FileOutputStream(path+Filename); while ((len = in.read(buffer)) != -1) { out.write(buffer, 0, len); } out.close(); in.close(); filepath = Downpath+Filename; } catch (Exception e) { System.out.println("----------" + Filename +"文件上传失败————————"); e.printStackTrace(); return R.error(); } return R.ok(filepath); } }

你可能感兴趣的:(Java学习,java,javascript)