SpringMvc本地上傳檔案

進化的程式猿boy發表於2020-11-11

需要注意的是要配置multipartResolver Bean物件

bean物件(SpringMvc.xml)

<bean id="multipartResolver"
      class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <property name="maxUploadSize" value="10485760"/>
</bean>

maven

<dependency>
    <groupId>com.sun.jersey</groupId>
    <artifactId>jersey-core</artifactId>
    <version>1.18.1</version>
  </dependency>
  <dependency>
    <groupId>com.sun.jersey</groupId>
    <artifactId>jersey-client</artifactId>
    <version>1.18.1</version>
  </dependency>
</dependencies>

html程式碼

<h2 style="color:palevioletred">SpringMvc檔案上傳方式</h2>
<form action="file/SpringMvcFileLoad" method="post" enctype="multipart/form-data">
    請選擇檔案上傳:<input type="file" name="SpringMvcfile">
    <input type="submit" value="提交">
</form>

java程式碼

@RequestMapping("/SpringMvcFileLoad")
    @ResponseBody
    public String SpingMvcFileLoad(MultipartFile SpringMvcfile,HttpServletRequest request) throws IOException {
        //定義圖片伺服器的請求路徑(也可以使用本地路徑)
       // String Path = request.getSession().getServletContext().getRealPath("/SpringMvcFileLoad/");
        String Path = "E:\\IdeaProjects\\springMvc_03_fileUpload\\target\\springMvc_03_fileUpload\\SpringMvcFileLoad";
		//建立file物件,向下路徑上傳檔案
        File fileObj = new File(Path);
        //是否存在路徑 不存在建立
        if(!fileObj.exists()){
            fileObj.mkdir();
        }
        //得到檔名
        String filename = SpringMvcfile.getOriginalFilename();
        //名稱使用uuid進行唯一合法
        String uuid = UUID.randomUUID().toString().replaceAll("-", "").toLowerCase();
        filename = uuid+"_"+filename;
        //寫入檔案(路徑、名字)
        SpringMvcfile.transferTo(new File(fileObj,filename));
        return "success";
    }

上一篇是request物件上傳檔案(有興趣可以看看)

相關文章