1. 程式人生 > ><SpringMvc>入門五 檔案上傳

<SpringMvc>入門五 檔案上傳

檔案上傳的必要條件:

  1.form表單的enctype取值必須是:mutipart/form-data (預設是:application/x-www-form-urlencoded)

  2.method屬性為:post

  3.提供一個文字選擇域<input type="file" />

        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId
> <version>1.3.3</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.6</version> </dependency>

1.傳統的方式上傳

form表單

    <form action="/fileupload/f1" method="post" enctype="multipart/form-data" >
        選擇檔案:<input type="file" name="upload">
                <input type="submit" value="上傳">
    </form>

controller類,生成的檔案在target根目錄下的uploads資料夾中

@Controller
@RequestMapping("/fileupload")
public class FileuploadController { /** * 傳統的檔案上傳方式 */ @RequestMapping("/f1") public String f1(HttpServletRequest request) throws Exception { //用fileupload元件完成檔案上傳 String path = request.getSession().getServletContext().getRealPath("/uploads"); //判斷該路徑是否存在 File file = new File(path); if(!file.exists()){ //建立該資料夾 file.mkdirs(); } //解析request物件,獲取檔案上傳項 DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); //解析request List<FileItem> items = upload.parseRequest(request); for (FileItem item : items) { //判斷當前item物件是否是檔案上傳項 if(item.isFormField()){ //說明普通表單項 }else { //說明檔案上傳項 String fileName = item.getName(); //把檔名稱設定為唯一值 uuid String uuid = UUID.randomUUID().toString().replace("-", ""); fileName = uuid +"_"+fileName; //完成檔案上傳 item.write(new File(path,fileName)); //刪除臨時檔案 item.delete(); } } return "success"; } }

2.springmvc檔案上傳

 

1.配置檔案解析器

    <!-- 配置檔案解析器物件,要求id名稱必須是multipartResolver -->
    <bean id="multipartResolver"
          class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!--位元組單位-->
        <property name="maxUploadSize" value="10485760"/>
    </bean>

2.頁面表單

    <%--springmvc模式--%>
    <form action="/fileupload/f2" method="post" enctype="multipart/form-data" >
        選擇檔案:<input type="file" name="upload">
        <input type="submit" value="上傳">
    </form>

3.controller

    /**
     * springmvc模式的上傳
     */
    @RequestMapping("/f2")
    public String f2(HttpServletRequest request, MultipartFile upload) throws IOException {
        String path = request.getSession().getServletContext().getRealPath("/uploads");
        File file = new File(path);
        if(!file.exists()){
            file.mkdirs();
        }
        //獲取檔名字
        String filename = upload.getOriginalFilename();
        String uuid = UUID.randomUUID().toString().replace("-", "");
        filename = uuid +"_"+filename;
        //完成上傳
        upload.transferTo(new File(path,filename));
        return "success";
    }