当前位置: 移动技术网 > IT编程>开发语言>Jquery > java 文件上传

java 文件上传

2020年03月16日  | 移动技术网IT编程  | 我要评论

一、前端页面

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; }

 



如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网