日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

文件的上传和下载---学习笔记

發布時間:2023/12/20 编程问答 24 豆豆
生活随笔 收集整理的這篇文章主要介紹了 文件的上传和下载---学习笔记 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

文件上傳原理

在TCP/IP中,最早出現的文件上傳機制是FTP。它是將文件由客戶端發送到服務器的標準機制。
但是JSP編程中不能使用FTP方法來上傳文件,這是由JSP運行機制所決定的。

JSP中上傳文件的解決方式:
通過為表單元素設置
Method = “post”
enctype = “multipart/form-data”
屬性,讓表單提交的數據以二進制編碼的方式提交,在接受此請求的Servlet中用二進制流來獲取內容,就可以取得上傳文件的內容,從而實現文件的上傳。

表單中enctype屬性說明:
enctype屬性的值有三種:

  • application/x-www-form=urlencoded:這是默認編碼方式,它只處理表單域里的value屬性值,采用這種編碼方式的表單會將表單域的值處理成URL編碼方式。
  • multipart/form-data:這種編碼方式的表單會以二進制流的方式來處理表單數據,這種編碼方式會把文件域指定文件的內容也封裝到請求參數里。
  • text/plain:這種方式主要適用于直接通過表單發送郵件的方式

文件上傳的實現步驟:

  • 環境搭建:配置web.xml創建UploadServlet
  • 前臺頁面配置:Form的method設置為post,enctype設置為multipart/form-data
  • 后臺Servlet實現:保存上傳文件
  • 上傳文件的后臺實現的具體步驟:

  • 獲取request當中的流信息,保存到臨時文件
  • 從臨時文件當中得到上傳的文件名及文件內容起止位置
  • 根據文件起止位置,讀取上傳文件內容,保存到本地
  • 文件的上傳:

    //文件上傳private void uploadFile(HttpServletRequest request, HttpServletResponse response)throws IOException, FileNotFoundException, ServletException {// 從request當中獲取流信息InputStream is = request.getInputStream();// 在本地創建臨時文件String tempFileName = "C:\\Users\\Administrator\\Desktop\\tempFile";File tempFile = new File(tempFileName);// 將request請求中的所有信息寫入臨時文件中FileOutputStream fos = new FileOutputStream(tempFile);byte[] b = new byte[1024];int n;while ((n = is.read(b)) != -1) {fos.write(b, 0, n);}fos.close();is.close();// 獲取臨時文件中的上傳文件的文件名RandomAccessFile randomFile = new RandomAccessFile(tempFile, "r");randomFile.readLine();// 讀取第一行數據String str = randomFile.readLine();// 讀取第二行的內容int beginIndex = str.lastIndexOf("\\") + 1;System.out.println("開始位置:"+beginIndex);int endIndex = str.lastIndexOf("\"");String filename = str.substring(beginIndex, endIndex);System.out.println("文件名:"+filename);//獲取文件內容的開始位置randomFile.seek(0);//重新將定位文件指針定位到文件頭long startPosition = 0;int i = 1;while((n = randomFile.readByte())!=-1&&i<=4){if(n=='\n'){startPosition = randomFile.getFilePointer();i++;}}startPosition = randomFile.getFilePointer()-1;//獲取文件內容的結束位置randomFile.seek(randomFile.length());//定義文件指針到文件結尾long endPosition = randomFile.getFilePointer();int j = 1;while(endPosition>=0&&j<=2){endPosition--;randomFile.seek(endPosition);if(randomFile.readByte()=='\n'){j++;}}endPosition = endPosition-1;//設置保存上傳文件的路徑String realPath = getServletContext().getRealPath("/")+"images";System.out.println("上傳文件的路徑:"+realPath);File fileupload = new File(realPath);if(!fileupload.exists()){fileupload.mkdir();}File saveFile = new File(realPath,filename);RandomAccessFile randomAccessFile = new RandomAccessFile(saveFile, "rw");//從臨時文件當中讀取文件內容(根據起止位置獲取)randomFile.seek(startPosition);while(startPosition<endPosition){randomAccessFile.write(randomFile.readByte());startPosition = randomFile.getFilePointer();}//關閉輸入輸出流、刪除臨時文件randomFile.close();randomAccessFile.close();tempFile.delete();request.setAttribute("result", "上傳成功!");RequestDispatcher dispatcher = request.getRequestDispatcher("jsp/01.jsp");dispatcher.forward(request, response);}

    文件下載原理

    文件下載的步驟:

  • 需要通過HttpServletResponse.setContentType方法設置Content-Type頭字段的值,位瀏覽器無法使用某種方式或激活某個程序來處理的MIME類型,例如:“application/octet-stream”或“application/x-msdownload”等。
  • 需要通過HttpServletResponse.setHeader方法設置Content-Disposition頭的值為“attachment;filename=”文件名””。
  • 讀取下載文件,調用HttpServletResponse.getOutputStream方法返回的ServletOutputStream對象來向客戶端寫入附件文件內容。
  • 實現步驟:

  • 前臺頁面開發:通過超鏈接的方式發起文件下載請求
  • 配置web.xml文件:配置web.xml,創建DownloadServlet
  • 后臺Servlet實現:設置響應類型及響應頭輸出流寫入文件內容
  • 批量文件下載:

    // 批量下載文件private void downMore(HttpServletRequest req, HttpServletResponse resp) throws IOException {resp.setContentType("application/x-msdownload");resp.setHeader("Content-Disposition", "attachment;filename=test.zip");String path = getServletContext().getRealPath("/") + "images/";String[] filenames = req.getParameterValues("filename");String str = "";String rt = "/r/n";ZipOutputStream zos = new ZipOutputStream(resp.getOutputStream());for (String filename : filenames) {str += filename + rt;File file = new File(path+filename);zos.putNextEntry(new ZipEntry(filename));FileInputStream fis = new FileInputStream(file);byte[] b = new byte[1024];int n = 0;while ((n = fis.read(b)) != -1) {zos.write(b, 0, n);}zos.flush();fis.close();}zos.setComment("download success:" + rt + str);zos.flush();zos.close();}

    單文件下載:

    // 下載一個文件private void downOne(HttpServletRequest request, HttpServletResponse response)throws FileNotFoundException, IOException, ServletException {// 獲取文件下載路徑String path = getServletContext().getRealPath("/") + "images/";System.out.println("要下載的文件路徑地址:" + path);String filename = request.getParameter("filename");File file = new File(path + filename);if (file.exists()) {// 設置響應類型response.setContentType("application/x-msdownload");// 設置頭信息(作用:以附件的形式打開我們的下載文件,并且指定了附件的名稱,這樣下載的時候文件名就是這里設置的文件名稱了)response.setHeader("Content-Dispostion", "attachment;filename=\"" + filename + "\"");InputStream is = new FileInputStream(file);ServletOutputStream sos = response.getOutputStream();byte[] b = new byte[1024];int n;while ((n = is.read(b)) != -1) {sos.write(b, 0, n);}// 關閉流釋放資源sos.close();is.close();} else {request.setAttribute("errorResult", "文件不存在,下載失敗!");RequestDispatcher dispatcher = request.getRequestDispatcher("jsp/01.jsp");dispatcher.forward(request, response);}}

    使用SmartUpload實現文件的上傳和下載

    1.使用該組件可以輕松的實現上傳文件類型的限制,也可以輕易的取得文件上傳的名稱、后綴、大小等。
    2.SmartUpload本身也是一個系統提供的jar包,直接將此包放到classpath下即可,也可以拷貝到tomcat_home\lib目錄中

    使用SmartUpload實現文件的批量上傳:

    private void uploadFiles(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {//設置上傳文件保存路徑String filePath = getServletContext().getRealPath("/")+"images";System.out.println("上傳到的文件路徑地址:"+filePath);File file = new File(filePath);if(!file.exists()){file.mkdir();}String result = "上傳成功!";SmartUpload su = new SmartUpload();//初始化對象su.initialize(getServletConfig(), request, response);//設置上傳文件的大小(10M)su.setMaxFileSize(1024*1024*10);//設置上傳的所有文件的大小(100M)su.setTotalMaxFileSize(1024*1024*100);//設置上傳文件的的類型su.setAllowedFilesList("txt,jpg,gif");//設置禁止上傳文件的類型try {su.setDeniedFilesList("rar,jsp,js");//上傳文件su.upload();//將上傳文件保存在文件夾中(返回的是上傳的文件的個數)int count = su.save(filePath);System.out.println("上傳成功了"+count+"個文件!");} catch (Exception e) {result = "上傳失敗!";if(e.getMessage().indexOf("1015")!=-1){result = "上傳失敗:上傳文件類型不正確!";}else if(e.getMessage().indexOf("1010")!=-1){result = "上傳失敗:上傳文件的類型不正確!";}else if(e.getMessage().indexOf("1105")!=-1){result = "上傳失敗:上傳文件的大小大于允許上傳的最大值!";}else if(e.getMessage().indexOf("1110")!=-1){result = "上傳失敗:上傳文件的總大小大于允許上傳的最大值!";}e.printStackTrace();} //通過SmartUpload獲得上傳文件的其他屬性for(int i=0;i<su.getFiles().getCount();i++){org.lxh.smart.File tempFile = su.getFiles().getFile(i);System.out.println("----------------------");System.out.println("上傳的文件名:"+tempFile.getFileName());System.out.println("上傳的文件的大小:"+tempFile.getSize());System.out.println("上傳的擴展名:"+tempFile.getFileExt());System.out.println("上傳的文件的全名:"+tempFile.getFilePathName());System.out.println("----------------------");}request.setAttribute("result", result);request.getRequestDispatcher("jsp/02.jsp").forward(request, response);}

    使用SmartUpload實現文件的下載(單文件下載):

    //下載一個文件private void downOne(HttpServletRequest request, HttpServletResponse response) {String filename = request.getParameter("filename");SmartUpload su = new SmartUpload();try {su.initialize(getServletConfig(), request, response);su.downloadFile("/images/" + filename);} catch (Exception e) {e.printStackTrace();}}

    項目完整代碼的Github地址:

    總結

    以上是生活随笔為你收集整理的文件的上传和下载---学习笔记的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。