文件上传、下载

1.上传

importFile 是前台上传文件的name
private void upload(MultipartFile importFile, HttpServletRequest request){
    MultipartHttpServletRequest multipartRequest;
    File targetFile =null;
    List<List<String>> list=null;
    try {
        multipartRequest = (MultipartHttpServletRequest) request;
        String path = request.getSession().getServletContext().getRealPath("upload");
        //文件夹不存在创建文件夹
        File logoSaveFile = new File(path);
        if (!logoSaveFile.exists()) {
            logoSaveFile.mkdirs();
        }
        MultipartFile multipartFile = multipartRequest.getFile("importFile");
        String suffix ="."+ importFile.getOriginalFilename().substring(importFile.getOriginalFilename().lastIndexOf(".")+1);
        String filenametime =String.valueOf(System.currentTimeMillis());
        String flieName = filenametime+suffix;
        targetFile = new File(path, flieName);
        if (null != multipartFile && !multipartFile.isEmpty()) {
            multipartFile.transferTo(targetFile);
        }
        
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        //删除文件
        if (targetFile.exists()&&targetFile.isFile()){
            targetFile.delete();
        }
    }
}

2.下载

public void fileDownload(HttpServletRequest request, HttpServletResponse response)throws Exception{
    String path = request.getSession().getServletContext().getRealPath("/");
    //文件名
    String fileName="文件名字.XXX";
    //设置响应头和客户端保存文件名
    response.setCharacterEncoding("utf-8");
    response.setContentType("multipart/form-data");
    response.setHeader("Content-Disposition", "attachment;fileName="+java.net.URLEncoder.encode(fileName, "UTF-8"));
    InputStream inputStream = null;
    try {
        //打开本地文件流,webapp下file包
        inputStream = new FileInputStream(path+"/file/"+fileName);
        //激活下载操作
        OutputStream os = response.getOutputStream();
        //循环写入输出流
        byte[] b = new byte[2048];
        int length;
        while ((length = inputStream.read(b)) > 0) {
            os.write(b, 0, length);
        }
        os.close();
    } catch (Exception e){
        e.printStackTrace();
    }finally {
        if(inputStream!=null) {
            inputStream.close();
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值