• java文件上传


    技术架构: Struts2 + JSP + jQuery

    普通标签上传文件

    页面标签

    <tr>
        <td class="table_a_td_l">上传附件:</td>
        <td colspan="2" class="table_a_td_r">
            <input name="uploadFile" id="uploadFile" type="file" style="170px;" onchange="return saveData('uploadFile')" >
        </td>
    </tr>

    前端js

    function savaData(labelId) {
        //调用文件上传的JS方法
        var result = ajaxFileUpload(labelId, 30*1024*1024);
        
        if(result == 'false') {//返回false, 上传失败
            return false;
        }else {
            alert(result.fileName);    //原文件名
            alert(result.fileNewName); //新文件名
            alert(result.filePath);    //上传到磁盘路径
            return false;
        }
    }
    
    /**
     * 上传文件
     * labelId: 上传控件的Id
     * fileSizeLimit: 上传大小限制(字节)
     */
    function ajaxFileUpload(labelId, fileSizeLimit) {
        //获取到文件对象
        var file = $("#"+labelId)[0].files[0];
        result = "false";
        if(null != file) {
            var byteSize = file.size;
            if (byteSize > fileSizeLimit) {
                alert("上传文件大小不能超过"+fileSizeLimit/1024/1024+"MB!");
                return "false";
            }
            var data = new FormData();
            data.append("file", file);
            data.append("filename", file.name);
            $.ajax({
                    url : "uploadFile.action",
                    type : "POST",
                    async : false,
                    cache : false,
                    processData : false,// 告诉jQuery不要去处理发送的数据
                    contentType : false,
                    data : data,
                    complete:function(XMLHttpRequest,textStatus){  
                        if(textStatus=='timeout'){  
                            var xmlhttp = window.XMLHttpRequest ? new window.XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHttp");  
                            xmlhttp.abort();   
                            alert("网络超时"); 
                            return "false";
                        }  
                    }, 
                    success : function(data) {
                        if (data.isOk) {
                            //data={"isOk":"true/false", "fileName":"原文件名", "fileNewName":"新文件名", "filePath":"上传到磁盘路径"}
                            result = data;
                        } else {
                            alert(data.info);
                            return "false";
                        }
                    },
                    error : function(err) {
                        fileUploadFalg = false;
                        alert(err);
                        return "false";
                    },
                });
        }
        return result;
    }

    后台Java代码

    import org.apache.commons.io.FileUtils;
    import org.apache.commons.io.FilenameUtils;
    
    //用于返回json(setter/getter)
    private Map<String,Object> validateExists = new HashMap<String, Object>(); 
    //文件上传(setter/getter)
    private File file;
    private String fileName;
    
    @Action(value = "uploadFile", interceptorRefs = {
            @InterceptorRef(value = "fileUpload", params={"maximumSize", "314572800"}),
            @InterceptorRef(value = "basicStack")
            },
            results = { 
            @Result(name = "success", type = "json", params= {"root","validateExists"}) })
    public String uploadFile(){
        //通过config.properties配置一个文件存放路径, 如D:/upload/jrzx/
        String filePath = FilePathUtil.FILE_ROOT + FilePathUtil.SEPARATOR + Config.getProperty("file.jrzx.logo") + FilePathUtil.SEPARATOR;
        try {
            String storageFileName = generateFileName(fileName);
            if (null != file) {
                if (314572800 < file.length()) { //大小不能超过300M
                    validateExists.put("isOk", false);
                    validateExists.put("info", "文件大小不能超过300M");
                } else {
                    File path = new File(filePath + storageFileName);
                    if (path.exists()) {
                        FileUtils.deleteQuietly(path);
                    }
                    FileUtils.moveFile(file, path);
                    validateExists.put("fileName", fileName);
                    validateExists.put("fileNewName", storageFileName);
                    validateExists.put("filePath",FilePathUtil.getVirtualPathBya( filePath + storageFileName));
                    validateExists.put("isOk", true);
                    validateExists.put("info", "上传成功");
                }
            } else {
                validateExists.put("isOk", false);
                validateExists.put("info", "请选择正确的文件格式和文件大小");
            }
        } catch (Exception e) {
            e.printStackTrace();
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            e.printStackTrace(pw);
            log.error(sw.toString());
            validateExists.put("isOk", false);
            validateExists.put("info", "系统异常,请稍候重试!");
        }
        return SUCCESS;
    }
    
    private String generateFileName(String fileName) {
        String newFileName = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()) + (int)(Math.random()*9000+1000);
        String prefix = FilenameUtils.getExtension(fileName);
        if (!Tool.isEmpty(prefix)) {
            newFileName += "." + prefix;
        }
        return newFileName;
    }

    将上传控件修改为按钮(可以方便的修改样式)

    下面这种方式应该也适合用"点击图片上传文件", 暂未尝试, 应该没问题

    页面标签

    <td class="table_a_td_l">上传附件:</td>
    
    <!-- <td colspan="2" class="table_a_td_r">
        <input name="uploadFile" id="uploadFile" type="file"> onchange="return savaData('attributeId', 'uploadFile', 999*1024*1024)" 
    </td> -->
    
    <s:hidden name="news.filePath" ></s:hidden>
    <s:hidden name="news.fileOldPath" ></s:hidden>
    <s:hidden name="news.fileName" ></s:hidden>
    <s:hidden name="news.fileOldName" ></s:hidden>
    <td colspan="1" class="table_a_td_r">
        <label for="fileinp">
                <input type="button" value="选择文件">
                    <s:if test="news.fileName != null"><span id="uploadFileBtnText">${news.fileName}</span></s:if>
                    <s:else><span id="uploadFileBtnText">未选择任何文件</span></s:else>
                <input name="uploadFile" id="uploadFile" type="file"  onchange="return fileChange('未选择任何文件')">
                
        </label>&nbsp;
        <label>
            <input type="button" value="删除" onclick="deleteUploadFile('未选择任何文件')">
            <!-- <img src="${basePath}/images/sc.gif" alt="删除"width="37" height="19" border="0"  /> -->
        </label>
    </td>
    <style>
        label{
            position: relative;
        } 
        #uploadFile{
            position: absolute;
            left: 0;
            top: 0;
            opacity: 0;
        }
    </style>

    前端js

    //当附件信息变更时的操作
    function fileChange(defaultMsg) {
        var uploadFilename = $("#uploadFile").val();
        if(isEmpty(uploadFilename)) {
            $("#uploadFileBtnText").html(defaultMsg);
            $("#newsForm_news_fileName").val("")
        }else {
            var arr = uploadFilename.split("\");
            $("#uploadFileBtnText").html(arr[arr.length-1]);
            $("#newsForm_news_fileName").val(arr[arr.length-1])
        }
        
    }
    
    function deleteUploadFile(defaultMsg) {
        if(isEmpty($("#newsForm_news_fileName").val())){
            alert("不存在需要删除的附件!");
            return false;
        }
        
        if(confirm("你确定删除附件吗?
    
    删除附件需要提交后才能生效!")){
            $("#uploadFileBtnText").html(defaultMsg);
            $("#newsForm_news_fileName").val("")
            return false;
        }
        
    }
    
    function saveNews(){
        if(confirm("你确定提交吗?") && checkForm()){
            var hasFile = $("#uploadFileBtnText").html();
            var filePath = $("#newsForm_news_filePath").val();
            var fileName = $("#newsForm_news_fileName").val();
            var fileOldName = $("#newsForm_news_fileOldName").val();
            
            //只要存在数据, 那就上传数据(因为即使文件名相同, 内容可能变更了), 然后后台再删除旧的数据
            var result = "false";    var labelId = "uploadFile";   var fileSizeLimit = 999*1024*1024;
            if( !isEmpty(fileName) && !isEmpty($("#"+labelId)[0].files[0])) {
                result = ajaxFileUpload(labelId, fileSizeLimit); //上传文件
            }else { //不存在数据, 不需要上传
                result = {"filePath":"", "fileName":""}; 
            }
            
            //alert($("#uploadFileBtnText").html());
            if(result != 'false') {//如果返回false
                //alert("上传文件成功");
                //alert(result.fileName);    //原文件名
                //alert(result.fileNewName); //新文件名
                //alert(result.filePath);    //上传到磁盘路径
                //将当前的附件信息设置到隐藏域
                $("#newsForm_news_filePath").val(result.filePath);
                $("#newsForm_news_fileName").val(result.fileName);
                //提交表单,保存数据
                var rebutUrl = "saveNewsOfCs.action";
                //$("#domains").val(getSelectTree("showDomains"))
                $("#newsForm").attr("action", rebutUrl).submit();
                return true;
            }else {
            return false;
         } }else{ return false; } }
  • 相关阅读:
    mysql联合索引命中条件
    Shiro知识初探(更新中)
    Java中使用MongoTemplate进行分批处理数据
    Java中String时间范围比较
    使用ReentrantLock
    使用Condition
    python的坑--你知道吗?
    python基础--函数全解析(1)
    CSS基本语法及页面引用
    HTML学习汇总
  • 原文地址:https://www.cnblogs.com/jkfeng/p/11909707.html
Copyright © 2020-2023  润新知