1. 程式人生 > 程式設計 >ssm框架Springmvc檔案上傳實現程式碼詳解

ssm框架Springmvc檔案上傳實現程式碼詳解

一、上傳:

1)編寫前臺檔案上傳表單。Method必須為post,enctype為mutipart/form-data

<body>
<%--檔案上傳
   1)method必須指定為post
   2)enctype必須指定為multipart/form-data
--%>
<h1>頭像上傳</h1>
<form action="${pageContext.request.contextPath}/admin/headpic" method="post" enctype="multipart/form-data">
  選擇頭像:<input type="file" name="headpic"/>
<%--  ${param.屬性值}==request.getParameter(屬性值)--%>
  <input type="text" name="id" value="${param.id}">
  <input type="submit" value="上傳"/>
</form>
</body>

2)編寫控制層程式碼,獲取上傳的檔案資料,並儲存MultipartFile;

//MultipartFile:用來接收上傳的檔案,引數名與input的name一直
  //@SessionAttribute("admin"):獲取session域中的值
  //@RequestParam(required = false):指定對應的引數可以為空,不是必須有值
  @RequestMapping("/headpic")
  public String headPic(MultipartFile headpic,@RequestParam(required = false) Admin admin,Integer id) throws IOException {
    String filename = headpic.getOriginalFilename();
    System.out.println("上傳的檔名:"+filename);
    File file=new File("E:/headpic/"+filename);
    if (!file.getParentFile().exists()){
      file.getParentFile().mkdirs();//如果父目錄不存在,建立該目錄
    }
    //儲存檔案,將上傳的檔案內容寫入file
    headpic.transferTo(file);
    admin=new Admin(id);
    //將頭像訪問路徑儲存到物件中
    admin.setHeadpic("/head/"+filename);
    //更新使用者頭像資訊
    adminService.updateHeadPic(admin);
    return "redirect:list";
  }

3)在springmvc配置檔案中配置檔案上傳配置項。配置multipartResolver;

  <!--配置檔案上傳-->
  <bean id="multipartResolver"
     class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <!--設定檔案編碼格式-->
    <property name="defaultEncoding" value="UTF-8"/>
    <!--設定最大上傳大小-->
    <property name="maxUploadSize" value="10240000" />
  </bean>
<!--  資源對映,將請求地址對映到某個目錄或具體的磁碟路徑
   mapping:配置請求地址; location:配置檔案路徑
   請求地址:/head/logo.png==>E:/headpic/logo.png
-->
  <mvc:resources mapping="/head/**" location="file:E:/headpic/"></mvc:resources>
<!--  請求地址為/headimg/logo.png==>/WEB-INF/img/logo.png-->
  <mvc:resources mapping="/headimg/**" location="/WEB-INF/img/"></mvc:resources>

二、下載:

1) 獲取到下載檔案的路徑;

2) 讀取檔案內容到位元組陣列;

3) 返回位元組陣列,並宣告返回型別為stream,設定附件名稱;

@GetMapping("/headPicDownload")
  public ResponseEntity<byte[]> headPicDownload(String filename) throws IOException {
    //1、定位到檔案地址
    File file=new File("E:/headpic/"+filename);
    //2、讀取檔案內容
    byte[] bytes= FileUtils.readFileToByteArray(file);
    //3、設定http響應頭
    HttpHeaders headers = new HttpHeaders();
    //設定ContentType為stream
    headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
    //4、設定以附件形式開啟
    headers.setContentDispositionFormData("attachment",filename);
    //                內容  頭部資訊  http狀態碼
    return new ResponseEntity<byte[]>(bytes,headers,HttpStatus.CREATED);
  }
<td>
        <img style="width: 25px;height: 25px;border-radius: 50%;"
           src="${pageContext.request.contextPath}${admin.headpic}"/>
        <a href="${pageContext.request.contextPath}/admin/headPicDownload?filename=${fn:replace(admin.headpic," rel="external nofollow" /head/","" )}">下載</a>
      </td>

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。