java中文件上传和下载

1.文件上传到服务器指定位置

//1.获取要上传的原始文件名
String uploadFileName = file.getOriginalFilename();
//2.截取文件扩展名
String extendName = uploadFileName.substring(uploadFileName.lastIndexOf(".") + 1, uploadFileName.length());
//3.产生随机数(将文件加上随机数,防止文件重复)
String uuid = UUID.randomUUID().toString().replace("-", "").toUpperCase();
//4.生成的新的服务器文件名(防止服务器文件名重名)
String newFileName = uuid + "." + extendName;
//5.获取真实的服务器文件上传地址(服务器运行目录,最终上传的路径,"/docupload"为路径)
String filePath = request.getServletContext().getRealPath("/docupload") + "/" + newFileName;
//6.执行上传
file.transferTo(new File(filePath));
System.out.println("文件上传结束!");

2.从服务器指定路径中下载文件到个人目录下

//1.获取服务器中文件的地址
String path = request.getSession().getServletContext().getRealPath("/docupload");
//2.创建文件对象
File file = new File(path, fileName);
//3.判断文件是否存在
if (file.exists()) {
    try {
        //4.设置Http标头
        HttpHeaders headers = new HttpHeaders();
        //5.拼接新文件的名字
        String newFileName = document.getTitle() + "." + fileName.split("\\.")[1];
        //6.设置获取文件的字符集样式
        String downName = new String(newFileName.getBytes("UTF-8"), "ISO-8859-1");
        //7.设置以附件的形式下载
        headers.setContentDispositionFormData("attachment", downName);
        //8.设置文件内容以流的形式下载
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        //9.用springMVC提供的下载方式
        ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(FileUtils.readFileToByteArray(file), headers, HttpStatus.OK);
        return responseEntity;
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

3.java制作Excel表格,并通过流形式下载

List<Users> users = usersService.list(queryWrapper);

//导出数据到Excel
//1、在内存先创建工作簿对象
HSSFWorkbook workbook = new HSSFWorkbook();

//2、创建一个sheet
HSSFSheet sheet = workbook.createSheet("用户信息表");//Excel文档左下名
sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 5));

HSSFRow bTitleRow = sheet.createRow(0);//第一行设置标题
HSSFCell bTitleCell = bTitleRow.createCell(0);
bTitleCell.setCellValue("用户信息表");
HSSFCellStyle style = workbook.createCellStyle();
style.setAlignment(HorizontalAlignment.CENTER);//第一行标题文本居中格式

HSSFFont hssfFont = workbook.createFont();
hssfFont.setFontName("微软雅黑");
hssfFont.setColor((short) 6);

style.setFont(hssfFont);
bTitleCell.setCellStyle(style);

HSSFRow titleRow = sheet.createRow(1);//第一行为制作的标题
String[] titles = {"编号", "登录名", "用户名", "状态", "创建时间", "更新时间"};
for (int i = 0; i < titles.length; i++) {
    HSSFCell cell = titleRow.createCell(i);
    cell.setCellValue(titles[i]);
}
//将数据填入表格
for (int i = 0; i < users.size(); i++) {
    Users user = users.get(i);
    HSSFRow row = sheet.createRow(i + 2);

    HSSFCell cell_id = row.createCell(0);
    cell_id.setCellValue(user.getId());

    HSSFCell cell_login_name = row.createCell(1);
    cell_login_name.setCellValue(user.getLogin_name());
    HSSFCell cell_username = row.createCell(2);
    cell_username.setCellValue(user.getUsername());
    HSSFCell cell_status = row.createCell(3);
    cell_status.setCellValue(user.getStatus() == 1 ? "启动" : "禁用");
    HSSFCell cell_create_date = row.createCell(4);
    cell_create_date.setCellValue(user.getCreate_date());
    HSSFCell cell_update_date = row.createCell(5);
    cell_update_date.setCellValue(user.getUpdate_date());
}

// 生成文件
String fileName = "用户信息表.xls";
response.setContentType("application/vnd.ms-excel");
String contentDisposition = "";
if (request.getHeader("User-Agent").toLowerCase().indexOf("firefox") > 0) {
    contentDisposition = "attachment; filename=\"" + new String(fileName.getBytes("UTF-8"), "ISO8859-1") + "\"";// firefox浏览器
} else {
    contentDisposition = "attachment; filename=\"" + URLEncoder.encode(fileName, "UTF-8") + "\"";//  其余浏览器  包括IE浏览器
}
response.setHeader("Content-Disposition", contentDisposition);
response.setCharacterEncoding("UTF-8");

//把文件响应到输出流
ServletOutputStream outputStream = response.getOutputStream();
try {
    workbook.write(outputStream);
} catch (Exception e) {
    e.printStackTrace();
} finally {
    if (outputStream != null) {
        try {
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
System.out.println("Excel文件生成完毕!");
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值