JAVA编码(58)—— SpringMvc+easyui文件上传(Ajax提交form表单形式)

<!-- 上传文件 -->
<div id="uploadFiles" class="easyui-dialog"
     style="width: 500px; height: 200px; padding: 10px 20px" closed="true" align="center"
     data-options="modal:true,closed:true,resizable:true,collapsible:true,minimizable:true,maximizable:true"
     buttons="#uploadFile-buttons">
    <form id="uploadFormId" name="uploadForm" method="post" enctype="multipart/form-data">
        <table>
            <tr>
                <td>
                    <%--<input type="file" id="uploadId" name="file" style="width:200px;">--%>
                    <input class="easyui-filebox" id="fileUpload" name="fileUpload"
                           data-options="prompt:'Choose a file...'" style="width:250px;height:25px;"></td>
                </td>
            </tr>
            <tr>
                <td style="width:9%;">
                    <label>素材名称:</label>
                </td>
                <td style="width:26%;">
                    <input id="sucaiName" name="sucaiName" class="easyui-textbox"
                           data-options="prompt: '素材名称'" style="width:80%;">
                </td>
            </tr>
            <tr>
                <td></td>
                <td colspan="2"><label id="uploadFileName"></label></td>
            </tr>
            <tr>
                <td></td>
                <td colspan="2">
                    <label id="uploadFileInfo"></label>
                </td>
            </tr>
        </table>
    </form>
    <div id="uploadFile-buttons">
        <a href="#" class="easyui-linkbutton showbutton" iconCls="icon-ok" onclick="upload()">上传</a>
        <a href="#" class="easyui-linkbutton" iconCls="icon-cancel"
           onclick="javascript:$('#uploadFiles').dialog('close')">取消</a>
    </div>
</div>
/**
 * 文件上传
 */
function uploadFile() {
    $('#uploadFiles').dialog('open').dialog('setTitle', '文件上传');
}

function upload() {
    // //获取上传文件控件内容
    // var file = document.getElementById('uploadId').files[0];
    // //判断控件中是否存在文件内容,如果不存在,弹出提示信息,阻止进一步操作
    // if (_fn.empty(file)) {
    //     alert('错误,请选择文件');
    //     return;
    // }
    // uploadForm.action = basedir + "/Activityinfo/uploadForm.do";
    // uploadForm.submit();

    var formData = new FormData($("#uploadFormId")[0]);
    $.ajax({
        url: basedir + "/Activityinfo/uploadForm1.do",
        type: 'POST',
        data: formData,
        async: false,
        cache: false,
        contentType: false,
        processData: false,
        success: function (returnInfo) {
            //上传成功后将控件内容清空,并显示上传成功信息
            document.getElementById('fileUpload').value = null;
            document.getElementById('uploadFileInfo').innerHTML = "<span style='color:Red'>" + returnInfo + "</span>";
        },
        error: function (returnInfo) {
            //上传失败时显示上传失败信息
            document.getElementById('uploadFileInfo').innerHTML = "<span style='color:Red'>" + returnInfo + "</span>";
        }
    });
}
/**
     * 文件上传
     *
     * @return json
     */
    @RequestMapping(path = "/uploadForm1", method = RequestMethod.POST)
    @ResponseBody
    public InvokeResult uploadForm1(@RequestParam("sucaiName") String sucaiName, HttpServletRequest request) {
        try {
            System.out.println("文件上传");
            System.out.println("内容:" + sucaiName);
            System.out.println("内容:" + request.getParameter("sucaiName"));
            CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
            if (multipartResolver.isMultipart(request)) {
                MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
                Iterator<String> iterator = multipartRequest.getFileNames();
                while (iterator.hasNext()) {
                    MultipartFile multipartFile = multipartRequest.getFile(iterator.next());
                    System.out.println("源文件名:" + multipartFile.getOriginalFilename());
                    System.out.println("文件大小:" + multipartFile.getSize());
                    System.out.println("文件类型:" + multipartFile.getContentType().substring(5));
                    // 上传文件路径
                    String path = PubFun.getRealPath();
                    System.out.println("路径:" + path);
                    // 上传文件名
                    String filename = multipartFile.getOriginalFilename();
                    File filepath = new File(path, filename);
                    //判断路径是否存在,如果不存在就创建一个
                    if (!filepath.getParentFile().exists()) {
                        filepath.getParentFile().mkdirs();
                    }
                    // 将上传文件保存到一个目标文件当中
                    File file1 = new File(path + File.separator + filename);
                    System.out.println("文件大小1:" + file1.length());
                    multipartFile.transferTo(file1);
                    System.out.println("文件大小1:" + file1.length());
                }
            }
            return InvokeResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return InvokeResult.failure(e.getMessage());
        }
    }

 

/**
     * 获取项目的绝对路径 upload文件夹
     * 
     * @return
     */
    public static String getRealPath() {
        // TODO Auto-generated method stub
        PubFun pubFun = new PubFun();
        String realPath = pubFun.getClass().getResource("/").getPath();
        if (realPath.contains("WEB-INF/")) {
            realPath = "/"+realPath.substring(0, realPath.indexOf("WEB-INF/") - 1);
            realPath += "/upload/";
        } else if (realPath.contains("target/")) {
            realPath = realPath.substring(0, realPath.indexOf("target/") - 1);
            realPath += "/src/main/webapp/upload/";
        }
        return realPath;
    }

 

posted @ 2018-01-31 10:25  xu_shuyi  阅读(409)  评论(0编辑  收藏  举报