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

java文件上传下载

程序员文章站 2023-11-16 18:07:34
文件上传 文件下载 ......

文件上传

  @requestmapping(value="/uploadfile",method=requestmethod.post)
  public resultobject uploadfiles(@requestparam("file")multipartfile file,httpservletrequest request){
       resultobject rs = null;//返回上传完成信息
       string uploaddir = "files";//上传目录,文件保存在webapp下的files文件中
      if(!file.isempty()) {
          //可以对user做一些操作如存入数据库
          //以下的代码是将文件file重新命名并存入tomcat的webapp目录下项目的下级目录
          string filerealname = file.getoriginalfilename();                   //获得原始文件名;
          /*int pointindex = filerealname.indexof(".");                        //点号的位置
          string filesuffix = filerealname.substring(pointindex);             //截取文件后缀
          uuid fileid = uuid.randomuuid();                        //生成文件的前缀包含连字符
          string savedfilename = fileid.tostring().replace("-", "").concat(filesuffix);       //文件存取名
          */
         
          string saveddir = request.getsession().getservletcontext().getrealpath(uploaddir); //获取服务器指定文件存取路径
          file savedfile = new file(saveddir, filerealname);
          boolean iscreatesuccess;
          try {
              iscreatesuccess = savedfile.createnewfile();
              if (iscreatesuccess) {

                  file.transferto(savedfile);  //转存文件
                  rs = resultobject.getsuccessresult("上传文件成功");
                  long size = file.getsize();//获取文件大小

rs.setdata(uploaddir+filerealname); }else{ rs = resultobject.getfailresult("请修改文件名,重新上传"); } } catch (ioexception e) { e.printstacktrace(); } }else{ rs = resultobject.getfailresult("文件不能为空"); } return rs; }

文件下载

@requestmapping(value = "/filterpermission/appdownload", method = requestmethod.get)
    public void appdownload(httpservletrequest request, httpservletresponse response) {
        //url是上面文件上传的url
        download(url,request,response);
    }
public string download(string filepath, httpservletrequest request, httpservletresponse response) {
        bufferedinputstream bis = null;
        bufferedoutputstream bos = null;
        try {
            //获取文件名
            string filename = filepath.substring(filepath.lastindexof("/")+1);
            response.setcharacterencoding("utf-8");
            response.setcontenttype("application/octet-stream");
            //response.setcontenttype("application/force-download");
            //处理下载弹出框名字的编码问题
            response.setheader("content-disposition", "attachment;filename="
                    + new string( filename.getbytes("gb2312"), "iso8859-1" ));
            //获取文件的下载路径
            string path = request.getsession().getservletcontext().getrealpath(filepath);
            //利用输入输出流对文件进行下载
            inputstream inputstream = new fileinputstream(new file(path));
            //设置文件大小
            response.setheader("content-length", string.valueof(inputstream.available()));

            bis = new bufferedinputstream(inputstream);//构造读取流
            bos = new bufferedoutputstream(response.getoutputstream());//构造输出流
            byte[] buff = new byte[1024];
            int bytesread;
            //每次读取缓存大小的流,写到输出流
            while (-1 != (bytesread = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesread);
            }
            response.flushbuffer();//将所有的读取的流返回给客户端

        } catch (filenotfoundexception e) {
            e.printstacktrace();
        } catch (ioexception e) {
            e.printstacktrace();
        }finally{
            try{
                if(null != bis){
                    bis.close();
                }
                if(null != bos){
                    bos.close();
                }
            }catch(ioexception e){
                system.out.println("下载文件失败,"+"文件路径:"+filepath+e);
                logger.error("文件下载失败!", e);
            }
        }
        //  返回值要注意,要不然就出现下面这句错误!
        //java+getoutputstream() has already been called for this response
        return null;
    }