麻豆小视频在线观看_中文黄色一级片_久久久成人精品_成片免费观看视频大全_午夜精品久久久久久久99热浪潮_成人一区二区三区四区

首頁 > 開發 > Java > 正文

JavaWeb實現多文件上傳及zip打包下載

2024-07-14 08:41:35
字體:
來源:轉載
供稿:網友

本文實例為大家分享了javaweb多文件上傳及zip打包下載的具體代碼,供大家參考,具體內容如下

項目中經常會使用到文件上傳及下載的功能。本篇文章總結場景在JavaWeb環境下,多文件上傳及批量打包下載功能,包括前臺及后臺部分。 

首先明確一點: 

無法通過頁面的無刷新ajax請求,直接發下載、上傳請求。上傳和下載,均需要在整頁請求的基礎上實現。項目中一般通過構建form表單形式實現這一功能。

一、多文件上傳

項目需求為實現多圖片上傳功能。參考測試了網上找到的眾多插件方法后,決定選用Jquery原始上傳方案。以下按步驟貼出具體代碼。

1、HTML部分(可省略使用js構建)

<form id="uploadForm" method="post" enctype="multipart/form-data"> <input type="file" hidden name="fileImage" multiple/> <a href="javascript:void(0);" rel="external nofollow" rel="external nofollow" id="fileSubmit" onclick="uploadFileMulti()">上傳資料</a></form>

有幾點說明: 

1. form中 enctype=”multipart/form-data” 
2. 例中使用標簽,構建submit

2、JS部分

var formData = new FormData($("#uploadForm")[0]);formData.append("foldName", "datumList");  //設置父級文件夾名稱formData.append("oderCode", selfOrderCode);formData.append("datumType", datumType);$.ajax({ type: "POST", data: formData, url: "order/datumList/batchInsertDatumLists", contentType: false, processData: false, success: function (result) {  if (result.success) {   //清空框文件內容   $("#fileImage").val("");   var obj = document.getElementById('fileImage');   obj.outerHTML = obj.outerHTML;   refreshDatumList();   showSuccessToast(result.message);  } else {   showWarningToast(result.message);  } }, error: function () {  showErrorToast('請求失敗!') }});

以上有幾點說明: 

1. var formData = new FormData($(“#uploadForm”)[0]); 
2. 使用 formData.append(“oderCode”, selfOrderCode); 添加其他參數

Java后臺

MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request;List<MultipartFile> files = mRequest.getFiles("fileImage");

以上有幾點說明:

1. 獲取MultipartHttpServletRequest,對應file標簽的name

二、文件批量下載

本項目中,需求為批量下載某一批次文件。使用zip在服務器壓縮文件,之后將文件下載到客戶機。 
網上查詢,使用Java自帶的文件輸出類不能解決壓縮文件中文件名亂碼的問題。解決方法:使用ant.jar包,創建壓縮文件時,可以設置文件的編碼格式,文件名亂碼的問題就解決了。

HTML部分(可省略使用js構建)

<form id="uploadForm" method="post" enctype="multipart/form-data"> <div class="product-dl">  <input type="hidden" name="orderCode"/>  <input type="hidden" name="datumType"/>  <a href="javascript:void(0);" rel="external nofollow" rel="external nofollow" class="btn" onclick="batchDatumListDownLoad()">批量下載</a> </div></form>

JS部分

//批量下載function batchDatumListDownLoad() { var param = {}; param.datumType = $("#datumTypeQ").val(); if (param.datumType == -1) {  param.datumType = null;  //查詢所有 } param.orderCode = selfOrderCode; $("#uploadForm input[name=orderCode]").val(param.orderCode); $("#uploadForm input[name=datumType]").val(param.datumType); var form = $("#uploadForm")[0]; form.action = "order/datumList/batchDownLoadDatumList"; form.method = "post"; form.submit();//表單提交}

后臺部分

public void batchDownLoadDatumList(DatumListVo datumListVo, HttpServletResponse response) { try {  //查詢文件列表  List<DatumListVo> voList = datumListService.queryDatumLists(datumListVo);  //壓縮文件  List<File> files = new ArrayList<>();  for (DatumListVo vo : voList) {   File file = new File(vo.getDatumUrl());   files.add(file);  }  String fileName = datumListVo.getOrderCode() + "_" + datumListVo.getDatumType() + ".zip";  //在服務器端創建打包下載的臨時文件  String globalUploadPath = "";  String osName = System.getProperty("os.name");  if (osName.toLowerCase().indexOf("windows") >= 0) {   globalUploadPath = GlobalKeys.getString(GlobalKeys.WINDOWS_UPLOAD_PATH);  } else if (osName.toLowerCase().indexOf("linux") >= 0 || osName.toLowerCase().indexOf("mac") >= 0) {   globalUploadPath = GlobalKeys.getString(GlobalKeys.LINUX_UPLOAD_PATH);  }  String outFilePath = globalUploadPath + File.separator + fileName;  File file = new File(outFilePath);  //文件輸出流  FileOutputStream outStream = new FileOutputStream(file);  //壓縮流  ZipOutputStream toClient = new ZipOutputStream(outStream);  //設置壓縮文件內的字符編碼,不然會變成亂碼  toClient.setEncoding("GBK");  ZipUtil.zipFile(files, toClient);  toClient.close();  outStream.close();  ZipUtil.downloadZip(file, response); } catch (Exception e) {  e.printStackTrace(); }}

其中ZipUtil.java

/** * 壓縮文件列表中的文件 * * @param files * @param outputStream * @throws IOException */public static void zipFile(List files, ZipOutputStream outputStream) throws IOException, ServletException { try {  int size = files.size();  //壓縮列表中的文件  for (int i = 0; i < size; i++) {   File file = (File) files.get(i);   try {    zipFile(file, outputStream);   } catch (Exception e) {    continue;   }  } } catch (Exception e) {  throw e; }}/** * 將文件寫入到zip文件中 * * @param inputFile * @param outputstream * @throws Exception */public static void zipFile(File inputFile, ZipOutputStream outputstream) throws IOException, ServletException { try {  if (inputFile.exists()) {   if (inputFile.isFile()) {    FileInputStream inStream = new FileInputStream(inputFile);    BufferedInputStream bInStream = new BufferedInputStream(inStream);    ZipEntry entry = new ZipEntry(inputFile.getName());    outputstream.putNextEntry(entry);    final int MAX_BYTE = 10 * 1024 * 1024; //最大的流為10M    long streamTotal = 0;      //接受流的容量    int streamNum = 0;      //流需要分開的數量    int leaveByte = 0;      //文件剩下的字符數    byte[] inOutbyte;       //byte數組接受文件的數據    streamTotal = bInStream.available();      //通過available方法取得流的最大字符數    streamNum = (int) Math.floor(streamTotal / MAX_BYTE); //取得流文件需要分開的數量    leaveByte = (int) streamTotal % MAX_BYTE;    //分開文件之后,剩余的數量    if (streamNum > 0) {     for (int j = 0; j < streamNum; ++j) {      inOutbyte = new byte[MAX_BYTE];      //讀入流,保存在byte數組      bInStream.read(inOutbyte, 0, MAX_BYTE);      outputstream.write(inOutbyte, 0, MAX_BYTE); //寫出流     }    }    //寫出剩下的流數據    inOutbyte = new byte[leaveByte];    bInStream.read(inOutbyte, 0, leaveByte);    outputstream.write(inOutbyte);    outputstream.closeEntry();  //Closes the current ZIP entry and positions the stream for writing the next entry    bInStream.close(); //關閉    inStream.close();   }  } else {   throw new ServletException("文件不存在!");  } } catch (IOException e) {  throw e; }}/** * 下載打包的文件 * * @param file * @param response */public static void downloadZip(File file, HttpServletResponse response) { try {  // 以流的形式下載文件。  BufferedInputStream fis = new BufferedInputStream(new FileInputStream(file.getPath()));  byte[] buffer = new byte[fis.available()];  fis.read(buffer);  fis.close();  // 清空response  response.reset();  OutputStream toClient = new BufferedOutputStream(response.getOutputStream());  response.setContentType("application/octet-stream");  response.setHeader("Content-Disposition", "attachment;filename=" + file.getName());  toClient.write(buffer);  toClient.flush();  toClient.close();  file.delete();  //將生成的服務器端文件刪除 } catch (IOException ex) {  ex.printStackTrace(); }}

以上基本滿足文件上傳下載所需。

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VeVb武林網。


注:相關教程知識閱讀請移步到JAVA教程頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 亚洲精品午夜在线 | 91免费高清视频 | 激情欧美在线 | 黄色网址免费在线播放 | 日本免费aaa观看 | www.91视频com | 中文字幕在线播放不卡 | 国产成人精品免费视频大全最热 | 欧美一级免费看 | 国产一国产精品一级毛片 | 精品乱码久久久久 | 国产日韩久久久久69影院 | 在线免费观看毛片视频 | 国产精品视频一区二区三区四 | 三人弄娇妻高潮3p视频 | 久久国产精品二国产精品中国洋人 | 日韩视频在线一区二区三区 | 欧美日韩1区2区 | av免费在线观看av | 久久亚洲精品久久国产一区二区 | 亚洲爱爱网站 | 午夜精品福利影院 | 久在线观看福利视频69 | 欧洲精品久久 | a级高清免费毛片av在线 | 羞羞电影在线观看 | av在线影片 | 久久密| 羞羞电影在线观看 | 免费黄色大片网站 | 久久久久亚洲美女啪啪 | 看片一区二区三区 | 免费特黄 | 成人福利视频网站 | 国产精品久久久久久久久久久久午夜 | 国产精品一区二区x88av | 免费看性xxx高清视频自由 | 国产午夜免费视频 | 精品久久久久久久久久久久包黑料 | 日韩精品免费一区二区三区 | 天天夜夜操操 |