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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM