java实现web端文件上传与下载

 在项目开发中经常会遇到文件的上传于下载功能,在此做详细的总结,以备不时之需~~

前端上传代码:

<input type="file" size="50" accept="application/pdf" name="file" id="fileId"/> 


注意: accept属性值是用于默认点击上传显示的文件格式,并不能限制上传格式,如要限制,还是后台校验,在此不做赘述.

此处以pdf为例

accept 支持全部格式参考:点此查看


后端代码:

  上传:

 MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;  
        CommonsMultipartFile applyFile = (CommonsMultipartFile) multipartRequest.getFile("file");  
            String versionId = sdf.format(now);//以当前时间为版本id--存在风险  
            String fileUrl = "";  
            if(applyFile != null){  
                String fileName = applyFile.getOriginalFilename();  
                if(fileName == null || "".equals(fileName)){  
                    return false;  
                }  
                System.out.println("文件名称:"+fileName);  
                // 获取路径  
                String applyPath = request.getSession().getServletContext()  
                        .getRealPath("/")+ "uploads/files/";  
  
                // 创建文件目录  
                File dirPath = new File(applyPath);  
                if (!dirPath.exists()) {  
                    dirPath.mkdirs();  
                }  
                  
                String prefix = fileName.substring(fileName.lastIndexOf(".")+1);//获取文件后缀名  
                String absFileUrl = applyPath + versionId +"."+prefix;//文件绝对路径  
                fileUrl = "uploads/files/" + versionId +"."+prefix;//相对路径  
                File uploadFile = new File(absFileUrl);  
                System.out.println("上传后文件路径:"+absFileUrl);  
                //上传  
                FileCopyUtils.copy(applyFile.getBytes(), uploadFile);  
            }  
下载:

public void download(HttpServletRequest request,HttpServletResponse response, String fileUrl, String fileName) {  
         java.io.BufferedInputStream bis = null;    
            java.io.BufferedOutputStream bos = null;    
            try {    
                // 客户使用保存文件的对话框:    
                fileUrl = new String(fileUrl.getBytes("utf-8"), "utf-8");    
                response.setContentType("application/x-msdownload");    
                response.setCharacterEncoding("utf-8");    
                response.setHeader("Content-disposition", "attachment; filename="    
                        + fileName);    
                // 通知客户文件的MIME类型:    
                bis = new java.io.BufferedInputStream(new java.io.FileInputStream(    
                        (fileUrl)));    
                bos = new java.io.BufferedOutputStream(response.getOutputStream());    
                byte[] buff = new byte[2048];    
                int bytesRead;    
                int i = 0;    
        
                while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {    
                    bos.write(buff, 0, bytesRead);    
                    i++;    
                }    
                bos.flush();    
            } catch (Exception e) {    
                e.printStackTrace();    
            } finally {    
                if (bis != null) {    
                    try {    
                        bis.close();    
                    } catch (IOException e) {    
                        // TODO Auto-generated catch block    
                        e.printStackTrace();    
                    }    
                    bis = null;    
                }    
                if (bos != null) {    
                    try {    
                        bos.close();    
                    } catch (IOException e) {    
                        // TODO Auto-generated catch block    
                        e.printStackTrace();    
                    }    
                    bos = null;    
                }    
            }    
    }


  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值