ExtJS文件上传到服务器

懵懂的女人 提交于 2020-01-25 04:44:25

ExtJS文件上传到服务器

ExtJS前台

文件上传到服务器端,也就是项目下
还可以从服务器端下载文件
根据需求从别的页传一个parent参数,查找parent目录下的文件,若无parent参数,结果为空。
filefield下写了一个多文件上传,但IE貌似不是很好用
图片列 写了一个判断文件类型,是图片的话展示图片,并且双击会放大。

<c:set var="ctx" value="${pageContext.request.contextPath}"/>
<script type="text/javascript">
    var parent = null;
    if (location.href.split('?')[1] != undefined) {
        var parameters = Ext.urlDecode(location.href.split('?')[1]);
        (parameters.parent != undefined) ? parent = parameters.parent : 0;
    }
    Ext.onReady(function () {
        Ext.QuickTips.init();
        Ext.getBody().mask('加载中...');

        var riderStore = Ext.create('Ext.data.Store', {
            storeId: 'riderStore',
            autoLoad: false,//true为自动加载
            loading: false,//自动加载时必须为true
            pageSize: 20,
            fields: ['parent', 'child', 'type'],
            proxy: {
                url: '${ctx}/rider/selectRider.json',
                type: 'ajax',
                async: true,//false=同步.
                actionMethods: {
                    read: 'POST'
                },
                extraParams: {},
                reader: {
                    type: 'json',
                    root: 'result',
                    totalProperty: 'total'
                }
            }
        });

        var formPanel = Ext.create('Ext.form.Panel', {
            id: 'formPanel',
            layout: 'column',
            frame: true,
            autoScroll: true,
            defaults: {
                labelAlign: 'right',
                labelWidth: 100,
                inputWidth: 140,
                margin: '4,0,0,0'
            },
            items: [{
                xtype: 'hiddenfield',
                name: 'parent',
                value: parent
            }, {
                xtype: 'filefield',
                id: 'multipartFiles',
                name: 'multipartFiles',
                fieldLabel: '附件',
                buttonText: '请选择',
                inputWidth: 300,
                allowBlank: false,
                multipleFn: function ($this) {   //多文件上传
                    var typeArray = ["application/x-shockwave-flash", "audio/MP3", "image/*", "flv-application/octet-stream"];
                    var fileDom = $this.getEl().down('input[type=file]');
                    fileDom.dom.setAttribute("multiple", "multiple");
                    fileDom.dom.setAttribute("accept", typeArray.join(","));
                },
                listeners: {
                    afterrender: function () {
                        this.multipleFn(this);
                    },
                    change: function () {
                        var fileDom = this.getEl().down('input[type=file]');
                        var files = fileDom.dom.files;
                        var str = '';
                        for (var i = 0; i < files.length; i++) {
                            str += files[i].name;
                            str += ' ';
                        }
                        Ext.getCmp('multipartFiles').setRawValue(str);

                        this.multipleFn(this);
                    }
                }
            }, {
                id: 'insert',
                xtype: 'button',
                text: '上传',
                handler: _insertFileUpload
            }, {
                id: 'select',
                xtype: 'button',
                text: '查询',
                handler: _selectRider
            }]
        });

        var riderPanel = Ext.create('Ext.grid.Panel', {
            id: 'riderPanel',
            store: riderStore,
            title: '文件表单',
            columnLines: true,
            frame: true,
            selModel: {
                selType: 'checkboxmodel',
                mode: 'SINGLE'
            },
            columns: [{
                xtype: 'actioncolumn',
                width: 280,
                dataIndex: 'child',
                text: '图片',
                align: 'center',
                renderer: function (value, metaData, record) {
                    if (record.get('type') == 'image/jpeg' || record.get('type') == 'image/png') {
                        var id = metaData.record.id;
                        Ext.defer(function () {
                            Ext.create('Ext.Img', {
                                height: 140,
                                width: 250,
                                src: 'downloadRider.json?child=' + value + '&parent=' + record.get('parent') + '&random=' + Math.random(),
                                renderTo: id,
                                listeners: {
                                    scope: this,
                                    el: {
                                        dblclick: function (e, a) {
                                            var winViewImage = Ext.create('Ext.Window', {
                                                width: 750,
                                                height: 500,
                                                maximizable: true,//窗体最大化按钮
                                                title: '图片',
                                                layout: "fit", //窗口布局类型
                                                modal: true, //是否模态窗口,默认为false
                                                resizable: false,//调整窗体大小
                                                closeAction: 'hide', //关闭窗体实际上是隐藏窗体并未关闭销毁此窗体对象(节约资源)
                                                plain: true,//窗体主体部分背景颜色透明
                                                draggable: true,//充许拖动窗体
                                                border: false,
                                                items: [Ext.create('Ext.Img', {
                                                    width: 750,
                                                    height: 500,
                                                    src: 'downloadRider.json?child=' + record.get('child') + '&parent=' + record.get('parent')
                                                })]
                                            });
                                            winViewImage.show();
                                        }
                                    }
                                }

                            })
                        }, 50);

                        return Ext.String.format('<div id="{0}"></div>', id);
                    }
                }
            }, {
                text: '文件名',
                dataIndex: 'child',
                style: 'text-align: center;',
                flex: 1
            }, {
                text: '操作',
                style: 'text-align: center;',
                width: 100,
                renderer: function (value, metaData, record, rowIndex, colIndex, store, view) {
                    return '<a href=javascript:_downloadRider()>下载</a>' + '&nbsp&nbsp&nbsp' + '<a href=javascript:_deleteRider()>删除</a>'
                }
            }],
            viewConfig: {
                emptyText: '无数据',
                enableTextSelection: true
            },
            dockedItems: [{
                xtype: 'pagingtoolbar',
                store: riderStore,
                dock: 'bottom',
                displayInfo: true
            }]
        });

        Ext.create('Ext.container.Viewport', {
            layout: {
                type: 'border',
                regionWeights: {
                    west: -1,
                    north: 1,
                    south: 1,
                    east: -1
                }
            },
            defaults: {
                border: false
            },
            items: [{
                region: 'north',
                items: [formPanel]
            }, {
                region: 'center',
                layout: 'fit',
                items: [riderPanel]
            }]
        });

        _init();
    });

    function _init() {
        for (var i = 0; i < Ext.data.StoreManager.getCount(); i++) {
            if (Ext.data.StoreManager.getAt(i).isLoading()) {
                return;
            }
        }

        _selectRider();
        Ext.getBody().unmask();
    }

    function _insertFileUpload() {
        Ext.getCmp('formPanel').getForm().submit({
            url: '${ctx}/rider/insertRider.json',
            submitEmptyText: false,
            waitMsg: '上传中',
            success: function (form, action) {
                Ext.example.msg('操作信息', '成功!');
                _selectRider();
            },
            failure: function (form, action) {
                switch (action.failureType) {
                    case Ext.form.action.Action.CLIENT_INVALID:
                        Ext.MessageBox.alert('提醒', "请选择附件");
                        break;
                    case Ext.form.action.Action.SERVER_INVALID:
                        Ext.MessageBox.alert('错误', action.result.message, Ext.MessageBox.ERROR);
                        break;
                    case Ext.form.action.Action.CONNECT_FAILURE:
                        Ext.MessageBox.alert('错误', Ext.MessageBox.ERROR);
                }
            }
        });
    }

    function _selectRider() {
        var riderStore = Ext.data.StoreManager.lookup('riderStore');
        if (parent != null || parent != undefined) {
            riderStore.proxy.extraParams['parent'] = parent;
        }
        riderStore.currentPage = 1;
        riderStore.load();
    }

    function _downloadRider() {
        var records = Ext.getCmp('riderPanel').getSelectionModel().getSelection();

        if (records.length == 0) {
            Ext.MessageBox.alert('警告', '不能选择为空', Ext.MessageBox.WARNING);
            return;
        }

        location.href = 'downloadRider.json?child=' + records[0].get('child') + '&parent=' + records[0].get('parent');
    }

    function _deleteRider() {
        var records = Ext.getCmp('riderPanel').getSelectionModel().getSelection();

        if (records.length == 0) {
            Ext.MessageBox.alert('警告', '不能选择为空', Ext.MessageBox.WARNING);
            return;
        }

        Ext.MessageBox.show({
            title: '请选择',
            msg: '删除',
            buttons: Ext.MessageBox.YESNO,
            icon: Ext.MessageBox.QUESTION,
            fn: function (btn) {
                if (btn == 'yes') {
                    Ext.Ajax.request({
                        url: '${ctx}/rider/deleteRider.json',
                        async: false,
                        params: {
                            'parent': records[0].get('parent'),
                            'child': records[0].get('child')
                        },
                        callback: function (options, success, response) {
                            if (success) {
                                var data = Ext.decode(response.responseText);
                                if (data.success) {
                                    Ext.example.msg('操作信息', '删除成功!');
                                    _selectRider();
                                } else {
                                    Ext.MessageBox.alert('错误', data.message, Ext.MessageBox.ERROR);
                                }
                            } else {
                                Ext.MessageBox.alert('错误', '服务器错误', Ext.MessageBox.ERROR);
                            }
                        }
                    });
                }
            }
        });
    }
</script>

效果图效果图
双击图片放大
在这里插入图片描述
从项目中下载文件
在这里插入图片描述

后台

主要是通过getContentType()方法 生成根目录截取编译文件名前的路径,再进行拼接 ,具体情况看代码以及注释

package com.newangels.pms.oracle.controller;

import com.newangels.pms.oracle.BaseUtils;
import org.apache.commons.io.FileUtils;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.activation.MimetypesFileTypeMap;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.*;

@Controller
@RequestMapping("/rider/")
public class Rider {

    /**
     * 附件管理页
     *
     * @return
     */
    @RequestMapping(value = "manageRider", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String manageUpload() {
        return "/Rider/manageRider";
    }

    /**
     * 附件查看页
     *
     * @return
     */
    @RequestMapping(value = "viewRider", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String manageUploadTask() {
        return "/Rider/viewRider";
    }

    /**
     * 添加附件
     *
     * @param parent
     * @param multipartFiles
     * @param request
     * @param response
     * @param session
     * @return
     */
    @RequestMapping(value = "insertRider", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public Map<String, Object> insertRider(String parent, @RequestParam MultipartFile[] multipartFiles, HttpServletRequest request, HttpServletResponse response, HttpSession session) {
        Map<String, Object> result = new HashMap<String, Object>();
        File file;
        String fileName;
        //根路径
        String realPath;
        //判断文件是否为空
        if (multipartFiles.length == 0) {
            result.put("message", "上传失败,请选择文件");
        } else {
            //根据parent组装根路径
            if (parent == null || "".equals(parent)) {
                //注意:如果出现两个文件文件名一致时,会导致后面的文件将前面的文件覆盖!
                //必须保证每个文件名都不一样! --> 利用随机数!
                //利用UUID类生成一组随机码! --> 将随机码当做文件名!
                //BaseUtils.getUuid()方法是将生成的UUID中的"-"替换为""
                String uuid = BaseUtils.getUuid();
                realPath = getConTextPath() + uuid;
            } else {
                realPath = getConTextPath() + parent;
            }
            for (int i = 0; i < multipartFiles.length; i++) {
                //生成文件名
                fileName = multipartFiles[i].getOriginalFilename();
                //生成路径
                file = new File(realPath + "\\" + fileName);
                //如果指定文件不存在,按照指定路径创建该文件!
                if (!file.exists()) {
                    file.mkdirs();
                }
                //文件上传到服务器
                try {
                    multipartFiles[i].transferTo(file);
                } catch (IOException e) {
                    result.put("success", false);
                }
            }
            result.put("success", true);
        }
        return result;
    }

    /**
     * 查询
     *
     * @param parent
     * @param request
     * @param response
     * @param session
     * @return
     */
    @RequestMapping(value = "selectRider", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public Map<String, Object> selectRider(String parent, HttpServletRequest request, HttpServletResponse response, HttpSession session) {
        List<Map<String, Object>> fileMapList = new ArrayList<Map<String, Object>>();
        Map<String, Object> result = new HashMap<String, Object>();
        List<File> fileList = new ArrayList<File>();//所有的路径
        List<String> fileName = new ArrayList<String>();//处理后的路径
        String newFile;
        //生成根路径
        String realPath = getConTextPath();
        //判断parent是否为空进行条件查询
        if (parent != null && !"".equals(parent)) {
            //调用方法查询,file填充到fileList
            readFile(fileList, realPath + "\\" + parent);
        } else {
            //返回空
            return null;  //parent不穿参则返回空 若想全查询 运行下面的代码
            //readFile(fileList, realPath);

        }
        //截取路径取后两段路径
        for (int i = 0; i < fileList.size(); i++) {
            newFile = fileList.get(i).toString().substring(realPath.length(), fileList.get(i).toString().length());
            fileName.add(newFile);
        }

        //查询所有文件名
        for (File f : fileList) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("child", f.getName());
            String parentPath = f.getParent();
            parentPath = f.toString().substring(realPath.length(), f.toString().length() - f.getName().length() - 1);
            if (parentPath == "upload") {
                parentPath = null;
            }
            map.put("type", getContentType(f.getParent() + "\\" + f.getName()));
            map.put("parent", parentPath);
            fileMapList.add(map);

        }

        result.put("result", fileMapList);
        result.put("success", true);
        return result;
    }

    /**
     * 递归查询目录下的所有文件
     *
     * @param fileList
     * @param fileDir
     * @return
     */
    private List<File> readFile(List<File> fileList, String fileDir) {
        File file = new File(fileDir);
        File[] files = file.listFiles();// 获取目录下的所有文件或文件夹
        if (files == null) {// 如果目录为空,直接退出
            return null;
        }
        // 遍历,目录下的所有文件
        for (File f : files) {
            if (f.isFile()) {
                fileList.add(f);
            } else if (f.isDirectory()) {
                readFile(fileList, f.getAbsolutePath());
            }
        }

        return fileList;
    }

    /**
     * 获取windows/linux的项目根目录
     *
     * @return
     */
    public String getConTextPath() {
        String fileUrl = Thread.currentThread().getContextClassLoader().getResource("").getPath();
        if ("usr".equals(fileUrl.substring(1, 4))) {
            fileUrl = (fileUrl.substring(0, fileUrl.length() - 16));//linux
        } else {
            fileUrl = (fileUrl.substring(1, fileUrl.length() - 16));//windows
            //截取PMS_TZGL-web
            int index = fileUrl.indexOf("PMS_TZGL-web");
            //生成新的路径
            fileUrl = fileUrl.substring(0, index) + "PMS_TZGL-web/src/main/webapp/upload/";
        }

        return fileUrl;
    }

    /**
     * 附件下载
     *
     * @param child
     * @param parent
     * @param request
     * @param response
     * @param session
     * @throws UnsupportedEncodingException
     */
    @RequestMapping(value = "downloadRider", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public void downloadRider(String child, String parent, HttpServletRequest request, HttpServletResponse response, HttpSession session) throws UnsupportedEncodingException {
        String fileName = getConTextPath() + parent + "/" + child;
        InputStream is = readLinesTest(fileName);

//        String agent = (String) request.getHeader("USER-AGENT");
//        if (agent != null && agent.toLowerCase().indexOf("firefox") > 0) {// 兼容火狐中文文件名下载
//            fileName = "=?UTF-8?B?" + (new String(Base64.encodeBase64(fileName.getBytes("UTF-8")))) + "?=";
//        }
//        else {
//            fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
//        }

        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=" + new String(child.getBytes("gb2312"), "ISO-8859-1"));// 下载模式
        ServletOutputStream out = null;
        try {
            out = response.getOutputStream();
            byte[] content = new byte[65535];
            int length = 0;
            while ((length = is.read(content)) != -1) {
                out.write(content, 0, length);
                out.flush();
            }
            out.close();
            is.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 读入文件
     *
     * @param fileName
     * @return
     */
    public InputStream readLinesTest(String fileName) {
        InputStream is = null;
        try {
            is = new FileInputStream(fileName);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        return is;
    }

    /**
     * 删除附件
     *
     * @param parent
     * @param child
     * @param request
     * @param response
     * @param session
     * @return
     */
    @RequestMapping(value = "deleteRider", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public Map<String, Object> deleteFile(String parent, String child, HttpServletRequest request, HttpServletResponse response, HttpSession session) {
        Map<String, Object> result = new HashMap<String, Object>();
        //生成根路径
        String realPath = getConTextPath();
        File file = new File(realPath + parent + "\\" + child);
        if (FileUtils.deleteQuietly(file)) {
            result.put("success", true);
        } else {
            result.put("success", false);
        }

        return result;
    }

    /**
     * 获取文件类型
     *
     * @param fileUrl
     * @return
     */
    public String getContentType(String fileUrl) {
        String contentType = null;
        try {
            contentType = new MimetypesFileTypeMap().getContentType(new File(fileUrl));
        } catch (Exception e) {
            e.printStackTrace();
        }

        return contentType;
    }

}


查询那里由于需求只要后面的路径以及前台需要树状展示,目前功能尚未完善,仅供参考

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!