欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java 文件上传下载

程序员文章站 2022-07-23 07:51:57
文件实体类 /** * 文件实体 * @author luochen */ @Entity @Table(name = "awards_attachment") public class AwardsAttachment { @Id @GeneratedValue private Long atta ......

文件实体类

Java 文件上传下载
/**
 * 文件实体
 * @author luochen
 */
@entity
@table(name = "awards_attachment")
public class awardsattachment {
    @id
    @generatedvalue
    private long attachmentid;
    /**
     * 文件类型
     */
    private string attachmenttype;
    /**
     * 文件名称
     */
    private string filename;
    /**
     * 文件路径
     */
    private string filepath;
    /**
     * 创建时间
     */
    private date createtime;
    /**
     * 修改时间
     */
    private date updatetime;
    /**
     * 删除标识[1:删除,0正常]
     */
    private string delflag;

    public string getdelflag() {
        return delflag;
    }

    public void setdelflag(string delflag) {
        this.delflag = delflag;
    }

    public long getattachmentid() {
        return attachmentid;
    }

    public void setattachmentid(long attachmentid) {
        this.attachmentid = attachmentid;
    }

    public string getattachmenttype() {
        return attachmenttype;
    }

    public void setattachmenttype(string attachmenttype) {
        this.attachmenttype = attachmenttype;
    }

    public string getfilename() {
        return filename;
    }

    public void setfilename(string filename) {
        this.filename = filename;
    }

    public string getfilepath() {
        return filepath;
    }

    public void setfilepath(string filepath) {
        this.filepath = filepath;
    }

    public date getcreatetime() {
        return createtime;
    }

    public void setcreatetime(date createtime) {
        this.createtime = createtime;
    }

    public date getupdatetime() {
        return updatetime;
    }

    public void setupdatetime(date updatetime) {
        this.updatetime = updatetime;
    }
}
view code

 

文件的服务类和实现类就不写了,就是一些增删改查的方法。

 

文件上传控制类

Java 文件上传下载
/**
 * 资源下载
 */
@restcontroller
@requestmapping("data")
public class datadownloadcontroller {


    @autowired
    private awardsattachmentservice awardsattachmentservice;



    private static final logger logger = loggerfactory.getlogger(datadownloadcontroller.class);

    /**
     * 上传文件
     *
     * @param upfile
     * @param type    文件类型
     * @param request
     */

    @postmapping("/upload")
    @apioperation(value = "上传文件", notes = "上传文件", httpmethod = "post", produces = mediatype.application_json_utf8_value)
    @apiimplicitparam(name = "upfile", value = "文件", required = true, datatype = "multipartfile", paramtype = "upfile")
    public jsonresponseext uploadfile(@requestparam(value = "file" ) multipartfile upfile, @requestparam(value = "type", required = false) string type, httpservletrequest request) {


        //日期路径
        string baseurl = new simpledateformat("yyyy/mm/dd").format(new date()) + "/";

        //string host = request.getheader("origin").substring(0, request.getheader("origin").lastindexof(":")) + ":" + request.getlocalport();
        string host = request.getscheme()+"://"+request.getservername() +":"+request.getlocalport();
        string prepath = "";
        //返回结果集合
        map<string, string> map = new hashmap<>();

        //路径前缀
        prepath = propertydbutil.getpropertieskey("datadownload");
        //文件名称
        string filename = upfile.getoriginalfilename();

        //文件路径
        string path = prepath + baseurl;

        //存入虚拟目录后的文件名
        //存入虚拟目录后的文件
        file uploadedfile = new file(path, filename);
        
        file dest = uploadedfile.getparentfile();
        //如果不存在目录就创建
        if (!dest.exists()) {
            dest.mkdirs();
        }
        
        //文件大小限制
        long size = uploadedfile.length() / 1024 / 1024;
        if (size >= 10) {
            return jsonresponseext.customfail("0032","上传文件的大小不能大于10mb");
        }
        try {
            //上传
            upfile.transferto(uploadedfile);
            
            //保存附件
            awardsattachment attachment = new awardsattachment();
            attachment.setfilepath(uploadedfile.getpath());
            if (!"".equals(type)) {
                attachment.setattachmenttype(type);
            }
            attachment.setfilename(filename);
            attachment.setcreatetime(new date());
            attachment.setdelflag("0");
            long id = awardsattachmentservice.addattachment(attachment).getattachmentid();
            //定义返回信息
            string origin = host + "/data/down/" + id;
            map.put("id", id + "");
            map.put("name", filename);
            map.put("filepath", uploadedfile.getpath());
            map.put("url", origin);

            return jsonresponseext.success(map);

        } catch (illegalstateexception e) {
            // todo auto-generated catch block
            e.printstacktrace();
        } catch (ioexception e) {
            // todo auto-generated catch block
            e.printstacktrace();
        }
        return jsonresponseext.customfail("0909","上传失败!");
    }




    @getmapping(value = "/down/{id}")
    public object demo(@pathvariable("id") string id, string path, httpservletrequest request, httpservletresponse response) {

        if (!"".equals(id)) {
            awardsattachment tbattachment = new awardsattachment();
            tbattachment.setattachmentid(long.parselong(id));
            awardsattachment awardsattachment = awardsattachmentservice.findbyattachment(tbattachment);

            try {
                // 下载本地文件
                string filename = awardsattachment.getfilename();
                // 读到流中
                inputstream instream = new fileinputstream(awardsattachment.getfilepath());
                // 设置输出的格式
                response.reset();
                //第一步:设置响应类型
                response.setcontenttype("application/force-download");
                response.addheader("content-disposition", "attachment; filename=\"" + filename + "\"");
                // 循环取出流中的数据
                byte[] b = new byte[100];
                int len;

                while ((len = instream.read(b)) > 0) {
                    response.getoutputstream().write(b, 0, len);
                }
                instream.close();
            } catch (ioexception e) {
                e.printstacktrace();
            }
        }
        return jsonresponseext.customfail("0033","error");
    }

 

    /**
     * 文件信息
     * @param attachmentinfo
     * @param response
     * @return
     */
    @getmapping(value = "/downfile")
    public jsonresponseext filedownload(awardsattachment attachmentinfo, httpservletresponse response,httpservletrequest request) {
        map<string, string> map = new hashmap<string,string>();
        string host = request.getscheme()+"://"+request.getservername() +":"+request.getlocalport();
        awardsattachment info = awardsattachmentservice.findbyattachment(attachmentinfo);
        string origin =host+"/data/down/" + info.getattachmentid();
        string filename = info.getfilename();

        map.put("url",origin);
        map.put("name",filename);
        map.put("path",info.getfilepath());
        return jsonresponseext.success(map);
    }








}
view code

 

 

 

页面

<span class="info-item-status approval" @click="downfile(associatedmsg.creditcodesample)"><i class="el-icon-tickets"></i></span>
//文件下载
    downfile(url){

      var elemif = document.createelement("iframe");
      elemif.src = url;
      elemif.style.display = "none";
      document.body.appendchild(elemif);

    },
associatedmsg.creditcodesample为文件路径,类似下面那种路径(路径加上文件id)。为什么用这种路径呢?其实是我的项目是前端和后端是分离的,所以前端的端口和后端的端口号是不一致的,同时如果是
直接根据文件id去访问那个下载接口,我发现是返回的是文件流,并不会自动弹出下载框进行下载。如果是文件流的形式还要弄成blob类型,而且文件名无法确定,如果要有文件的名称的话
好像还要发一个请求去获取文件的信息。如果存的是下面的链接地址形式,直接点击就会请求这个接口进行下载了。

Java 文件上传下载

文件流形式

let url = window.url.createobjecturl(new blob([文件流]))
let a= document.createelement('a');
a.style.display = 'none';
a.href = url;
a.setattribute('download', 文件名称及后缀);
document.body.appendchild(a)
a.click();


 如果你其他的实体类存的是文件的id,可以根据文件id 获取文件信息再下载。[

this.$sysapi.filemsg() ,这个其实就是一个get方法

]

download(row) {
        this.$sysapi.filemsg({"attachmentid":row.fileid}).then(res =>{
          console.log(res,"文件");
          var elemif = document.createelement("iframe");
          elemif.src = res.data.url;
          elemif.style.display = "none";
          document.body.appendchild(elemif);
        });
}