java 后台通过IO流把文件传到前端并下载

我的业务需求是两个不同的web程序放在不同的服务器上,web程序A要访问到web程序B上传上来的文件,所以用到了这一个IO读取文件的接口

     JAVA代码(排版有点问题  已经尽力补救了(:3_ヽ)_)

  1. import java.io.BufferedInputStream;
  2. import java.io.BufferedOutputStream;
  3. import java.io.File;
  4. import java.io.FileInputStream;
  5. import java.io.FileOutputStream;
  6. import java.io.IOException;
  7. import java.io.InputStream;
  8. import javax.servlet.ServletOutputStream;
  9. import javax.servlet.http.HttpServletRequest;
  10. import javax.servlet.http.HttpServletResponse;
  11.  
  12. @Controller
  13. @RequestMapping(value = "/manage")
  14. public class ManageAction{
  15. /**
  16. * 通过流把文件传到前台下载
  17. * @param request
  18. * @param response
  19. * @param id 第几个文件 (因为有多个文件 用;号隔开的)
  20. * @param tzggid 对应的通知公告id
  21. */
  22. @RequestMapping(value = "/findfile")
  23. @ResponseBody
  24. public void findfile(HttpServletRequest request,HttpServletResponse response,@RequestParam("id") String id,@RequestParam("tzggid") String tzggid) throws IOException {
  25. ServletOutputStream out = null;
  26. FileInputStream ips = null;
  27. List<Map<String, Object>> list = null; //此处为业务需要
  28. list = jdbcTemplate.queryForList("select fjaddress,fjname from tb_tzgg where id = ?",tzggid); //此处为业务需要
  29. if(list.size() > 0){
  30. try {
  31. String url = String.valueOf(list.get(0).get("fjaddress")).split(";")[Integer.valueOf(id)]; //此处为业务需要 如果是测试可以指定路径
  32. //获取文件存放的路径
  33. File file = new File(url);
  34. String fileName=file.getName();
  35. //获取到文字 数据库里对应的附件名字加上老的文件名字:filename 截取到后面的文件类型 例:txt 组成一个新的文件名字:newFileName
  36. String newFileName = String.valueOf(list.get(0).get("fjname")).split(";")[Integer.parseInt(id)]+"."+fileName.substring(fileName.lastIndexOf(".")+1);
  37. if(!file.exists()) {
  38. //如果文件不存在就跳出
  39. return;
  40. }
  41. ips = new FileInputStream(file);
  42. response.setContentType("multipart/form-data");
  43. //为文件重新设置名字,采用数据库内存储的文件名称
  44. response.addHeader("Content-Disposition", "attachment; filename="" + new String(newFileName.getBytes("UTF-8"),"ISO8859-1") + """);
  45. out = response.getOutputStream();
  46. //读取文件流
  47. int len = 0;
  48. byte[] buffer = new byte[1024 * 10];
  49. while ((len = ips.read(buffer)) != -1){
  50. out.write(buffer,0,len);
  51. }
  52. out.flush();
  53. }catch (Exception e){
  54. e.printStackTrace();
  55. }finally {
  56. try {
  57. out.close();
  58. ips.close();
  59. } catch (IOException e) {
  60. System.out.println("关闭流出现异常");
  61. e.printStackTrace();
  62. }
  63. }
  64. }
  65. return ;
  66. }
  67. }

前端访问:

接口访问信息

贴上我自己的数据库让你们更清晰一点


数据库图片

以上就是所有的java通过io流访问文件的后台全部代码了。希望能帮到你们

https://blog.csdn.net/L1481333167/article/details/81705769

原文地址:https://www.cnblogs.com/q1359720840/p/13839699.html