html+java超大視訊上傳解決方案
阿新 • • 發佈:2020-12-22
上週遇到這樣一個問題,客戶上傳高清視訊(1G以上)的時候上傳失敗。 一開始以為是session過期或者檔案大小受系統限制,導致的錯誤。 查看了系統的配置檔案沒有看到檔案大小限制, web.xml中seesiontimeout是30,我把它改成了120。 但還是不行,有時候10分鐘就崩了。 同事說,可能是客戶這裡伺服器網路波動導致網路連線斷開,我覺得有點道理。 但是我在本地測試的時候發覺上傳也失敗,網路原因排除。 看了日誌,錯誤為: java.lang.OutOfMemoryErrorJavaheapspace 上傳檔案程式碼如下: publicstaticStringuploadSingleFile(Stringpath,MultipartFilefile){ if(!file.isEmpty()){ byte[]bytes; try{ bytes=file.getBytes(); //Createthefileonserver FileserverFile=createServerFile(path,file.getOriginalFilename()); BufferedOutputStreamstream=newBufferedOutputStream( newFileOutputStream(serverFile)); stream.write(bytes); stream.flush(); stream.close(); logger.info("ServerFileLocation=" +serverFile.getAbsolutePath()); returngetRelativePathFromUploadDir(serverFile).replaceAll("\\\\","/"); }catch(IOExceptione){ //TODOAuto-generatedcatchblock e.printStackTrace(); System.out.println(e.getMessage()); } }else{ System.out.println("檔案內容為空"); } returnnull; } 乍一看沒什麼大問題,我在stream.write(bytes);這句加了斷點,發覺根本就沒走到。 而是在bytes=file.getBytes();就報錯了。 原因應該是檔案太大的話,位元組數超過Integer(Bytes[]陣列)的最大值,導致的問題。 既然這樣,把檔案一點點的讀進來即可。 修改上傳程式碼如下: publicstaticStringuploadSingleFile(Stringpath,MultipartFilefile){ if(!file.isEmpty()){ //byte[]bytes; try{ //bytes=file.getBytes(); //Createthefileonserver FileserverFile=createServerFile(path,file.getOriginalFilename()); BufferedOutputStreamstream=newBufferedOutputStream( newFileOutputStream(serverFile)); intlength=0; byte[]buffer=newbyte[1024]; InputStreaminputStream=file.getInputStream(); while((length=inputStream.read(buffer))!=-1){ stream.write(buffer,0,length); } //stream.write(bytes); stream.flush(); stream.close(); logger.info("ServerFileLocation=" +serverFile.getAbsolutePath()); returngetRelativePathFromUploadDir(serverFile).replaceAll("\\\\","/"); }catch(IOExceptione){ //TODOAuto-generatedcatchblock e.printStackTrace(); System.out.println(e.getMessage()); } }else{ System.out.println("檔案內容為空"); } returnnull; } 效果展示:
詳細程式碼可以參考一下這篇文章:http://blog.ncmem.com/wordpress/2019/08/09/java%e5%a4%a7%e6%96%87%e4%bb%b6%e4%b8%8a%e4%bc%a0/