zoukankan      html  css  js  c++  java
  • Java实现文件的上传下载(含源代码和jar包)

    1.需要使用的jar包

    链接:https://pan.baidu.com/s/1IaxQRSwfzxDpe4w4JiaEKw
    提取码:xwtz

    2.如果想实现文件的下载,需要创建一张表,表的结构为

    id url(id为查找依据,url为文件名即可)

     2.文件的上传

    该方法我是建立在SpringBoot框架中实现的,实际上这并不是必要的。

    主要的是参数file是上传的文件信息,即路径相关。path的路径为获取的,使用与linux与windows系统,如果服务器固定,可以将path路径写成绝对路径。

    上传之后需要将文件名存进数据库中,并且对应唯一的id方便下载使用。

    后台

    @RequestMapping("upload")
        public String testupload(@RequestParam("uploadfile") MultipartFile file,HttpServletRequest request) throws IllegalStateException, IOException{
            System.out.println("上传");
            if(!file.isEmpty()) {//上传文件路径
                String path = request.getSession().getServletContext().getRealPath(File.separator+"WEB-INF"+File.separator+"testupload");
            //path="H:"+File.separator+"Demo"; 如果写绝对路径可用这个path覆盖上边
    //上传文件名 String filename = file.getOriginalFilename(); File filepath = new File(path,filename); //判断路径是否存在,如果不存在就创建一个 if (!filepath.getParentFile().exists()) { filepath.getParentFile().mkdirs(); } //将上传文件保存到一个目标文件当中 file.transferTo(new File(path + File.separator + filename)); userService.insertFileByFileName(filename); //将文件的名字存入数据库 //输出文件上传最终的路径 测试查看 return String.valueOf(file.getSize()); } else { return "0"; } }

    前台

    <form id="fileform" method="post" enctype="multipart/form-data">
    <input type="file" id="fileupload" name="uploadfile"/>
    <button id="upload_btn">上传文件</button>
    </form>
    
    
    $("#upload_btn").click(function(){
    var form = new FormData(document.getElementById("fileform"));
        $.ajax({
            type:"post",
            url:"/user/upload",
            data:form,
            processData:false,
            contentType:false,
            dataType:'text',
            success:function(data){
                    alert(data);
            }
        });
    });

    3.文件的下载(注)

    ids为传入的参数,为数据库中对应文件名的id,根据id查找到文件名,

    path为上传的文件路径,然后将路径与文件名拼接输出路径即为下载路径。

    注:下载的请求不能使用ajax,具体原因不清楚,我使用ajax多次尝试失败,改用a标签直接请求然后成功。

    后台

    @RequestMapping(value = "downloadfile",produces = "application/json;charset=utf-8")
        public void downloadlm(HttpServletRequest request,HttpServletResponse response,String ids,Model model) throws IOException {
            int id=Integer.parseInt(ids);
            System.out.println("进入下载文件");
            Myfile myFile = userService.selectFileById(id);
            
            String path = request.getSession().getServletContext().getRealPath(File.separator+"WEB-INF"+File.separator+"testupload");
            path="H:"+File.separator+"Demo";
            String filename=myFile.getUrl().substring(myFile.getUrl().lastIndexOf("\")+1);    
            System.out.println(filename+"=======================================");
            File file = new File(path+File.separator+filename);
            System.out.println(file.getPath());
            //设置响应的头信息,解决文件名为中文乱码的问题
            response.setHeader("content-disposition", "attachment;filename="+URLEncoder.encode(file.getName(), "utf-8"));
            //使用文件输入流读取下载文件信息
            FileInputStream in = new FileInputStream(file);
            //得到响应流中的输出流
            OutputStream out = response.getOutputStream();
            //建立一个缓存区
            byte[] buffer = new byte[1024];
            
            int len = 0;
            //把输入流中的数据通过循环写入到响应流中
            while((len = in.read(buffer)) > 0) {
                out.write(buffer,0,len);
            }
            
            
            in.close();
            out.close();
            
        }

    前台:

    <a id="down_file_btn"  href="/user/downloadfile?ids=1">下载</a>

  • 相关阅读:
    数值分析实验之平方根法解线性方程组(MATLAB代码)
    Packet Tracer 下载方法
    注册 Netacad (思科)账户 超详细流程
    数值分析实验之非线性方程求根(Python 现)
    数值分析实验之非线性方程求根(MATLAB实现)
    数值分析实验之矩阵的LU分解及在解线性方程组中的应用(java 代码)
    数值分析实验之矩阵的LU分解及在解线性方程组中的应用(MATLAB 代码)
    数值分析实验之矩阵的LU分解及在解线性方程组中的应用(Python 代码)
    数值分析实验之数值积分法(MATLAB代码)
    在python3中安装mysql扩展,No module named 'ConfigParser'
  • 原文地址:https://www.cnblogs.com/wys-373/p/11455839.html
Copyright © 2011-2022 走看看