国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發(fā) > AJAX > 正文

SpringMVC+Ajax實(shí)現(xiàn)文件批量上傳和下載功能實(shí)例代碼

2024-09-01 08:27:02
字體:
供稿:網(wǎng)友

今天做了文件的上傳下載,小小總結(jié)一下,基本的web項(xiàng)目建立及SpringMVC框架搭建此處不詳細(xì)寫出來了。

上傳form:

<form id="uploadfiles" enctype="multipart/form-data">    <input type="file" multiple="multiple" id="file_upload" name="file_upload" />     <input type="button" value="上傳" onclick="upload()" /></form>

上傳Ajax:

<script type="text/javascript">/* * 上傳文件 */function upload(){  var formData = new FormData($( "#uploadfiles" )[0]);   $.ajax({      type: "post",      url: "./path/upload",      dataType: "json",      data: formData,      /**         *必須false才會自動加上正確的Content-Type         */       contentType : false,       /**         * 必須false才會避開jQuery對 formdata 的默認(rèn)處理         * XMLHttpRequest會對 formdata 進(jìn)行正確的處理         */       processData : false,      success: function(data){//從后端返回數(shù)據(jù)進(jìn)行處理       if(data){         alert("上傳成功!");       }else{         alert("上傳失敗!");       }      },      error: function(err) {//提交出錯        $("#msg").html(JSON.stringify(err));//打出響應(yīng)信息        alert("服務(wù)器無響應(yīng)");       }     });}</script>

spring.xml配置加上:

<!-- 配置文件上傳 -->  <bean id="multipartResolver"    class="org.springframework.web.multipart.commons.CommonsMultipartResolver">    <!-- 默認(rèn)編碼 -->    <property name="defaultEncoding" value="utf-8" />    <!-- 文件大小最大值 -->    <property name="maxUploadSize" value="10485760000" />    <!-- 內(nèi)存中的最大值 -->    <property name="maxInMemorySize" value="40960" />  </bean>controller:/*   * 上傳多個文件   */  @RequestMapping(value = "/upload", produces = "application/json;charset=UTF-8")  public @ResponseBody  boolean uploadFiles(@RequestParam("file_upload") MultipartFile [] files) {    boolean result = false;    String realPath;    for(int i=0;i<files.length;i++){      if (!files[i].isEmpty()) {           String uniqueName=files[i].getOriginalFilename();//得到文件名          realPath="E:"+File.separator+uniqueName;//文件上傳的路徑這里為E盤          files[i].transferTo(new File(realPath));  // 轉(zhuǎn)存文件          result = true;              } catch (Exception e) {           e.printStackTrace();         }       }    }    return result;  }

下載的jsp頁面代碼根據(jù)需求不同自己設(shè)計,這里給出controller代碼:

/*   * 下載多個文件   */  @RequestMapping(value = "/download")  public void downloadFiles(HttpServletResponse response) {    String str= request.getParameter("rows");//下載文件信息,包括文件名、存儲路徑等    JSONArray path=(JSONArray) JSONArray.parse(request.getParameter("rows"));    Path paths[]=new Path[path.size()];    paths = JSONArray.parseArray(str, Path.class).toArray(paths);    String uri = "d:"+ File.separator + "mldn.zip";//臨時文件存儲路徑    File zipFile = new File(uri) ;  // 定義壓縮文件名稱     ZipOutputStream zipOut = null;// 聲明壓縮流對象     InputStream input = null;    //將要壓縮的文件加入到壓縮輸出流中    try {      zipOut = new ZipOutputStream(new FileOutputStream(zipFile));    } catch (FileNotFoundException e) {      e.printStackTrace();    }    for(int i = 0;i<paths.length;i++){      File file = new File(paths[i].getUri()+File.separator+paths[i].getFilename());      try {        input = new FileInputStream(file) ;// 定義文件的輸入流         zipOut.putNextEntry(new ZipEntry(file.getName())) ; // 設(shè)置ZipEntry對象       } catch (Exception e) {        e.printStackTrace();      }     }    //將文件寫入到壓縮文件中    int temp = 0 ;     try {      while((temp=input.read())!=-1){ // 讀取內(nèi)容         zipOut.write(temp) ;  // 寫到壓縮文件中       }    } catch (IOException e) {      e.printStackTrace();    }finally{       try {        input.close() ;        zipOut.close() ;       } catch (IOException e) {        e.printStackTrace();      }     }    try {      // 以流的形式下載文件。      BufferedInputStream fis = new BufferedInputStream(new FileInputStream(zipFile));      byte[] buffer = new byte[fis.available()];      fis.read(buffer);      fis.close();      // 清空response      response.reset();      OutputStream toClient = new BufferedOutputStream(response.getOutputStream());      response.setContentType("application/x-msdownload;");       response.setHeader("Content-Disposition", "attachment;filename=" + zipFile.getName());      toClient.write(buffer);      toClient.flush();      toClient.close();      zipFile.delete();    //將生成的服務(wù)器端文件刪除    }     catch (IOException ex) {      ex.printStackTrace();    }    }            
發(fā)表評論 共有條評論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 寻甸| 天柱县| 庐江县| 达尔| 出国| 子长县| 丰县| 巍山| 左权县| 安多县| 习水县| 永寿县| 汾西县| 吴桥县| 神木县| 云龙县| 那曲县| 全椒县| 五寨县| 越西县| 建水县| 咸丰县| 当涂县| 塔河县| 富平县| 长治市| 进贤县| 崇仁县| 沁源县| 新营市| 奈曼旗| 龙胜| 巴彦淖尔市| 嫩江县| 峨边| 岳池县| 屯留县| 蒙阴县| 横山县| 武功县| 彭州市|