1. 程式人生 > >Springmvc下實現多個圖片檔案的上傳與儲存

Springmvc下實現多個圖片檔案的上傳與儲存

現在許多頁面都開始要求實現不定量圖片上傳,這裡給出一種利用java.MultipartFile類的方法,希望能對大家有幫助。

第一步新增jar包:在pom.xml裡面新增如下程式碼

<!-- uploadify檔案上傳元件 -->  
        <dependency>  
            <groupId>commons-fileupload</groupId>  
            <artifactId>commons-fileupload</artifactId>  
            <version
>
1.3.1</version> </dependency>

然後是在配置檔案applicationContext.xml中新增bean:

<!-- 支援檔案上傳 -->  
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
         <!-- 請求編碼格式 -->  
         <property name="defaultEncoding"
value="utf-8">
</property> <!-- 上傳檔案大小(單位:位元組) --> <property name="maxUploadSize" value="50000000"></property> <!-- 緩衝區大小(單位:KB) --> <property name="maxInMemorySize" value="1024"></property> </bean>

這裡給出前端測試介面filesTest.jsp:

<form action="/files/test" method="post" enctype="multipart/form-data">//表示psot的內容是multipart/form-data

        選擇圖片:<input type="file" name="files">
    <p>
        選擇圖片:<input type="file" name="files">
    <p>
    //這裡無論幾個上傳按鈕都ok
        <input type="submit" value="提交">
</form>

然後是後臺controller:

    @Autowired
    private HttpServletRequest request;

    @RequestMapping(value = "files/test",method = RequestMethod.POST)
    @ResponseBody
    public JSONObject filesUpload(@RequestParam("files") MultipartFile[] files) //以MultipartFile型別陣列形式接受傳過來的圖片檔案
    {
        JSONObject json = new JSONObject(); 
        //判斷file陣列不能為空並且長度大於0
        if(files!=null&&files.length>0){
            //迴圈獲取file陣列中得檔案
            for(int i = 0;i<files.length;i++){
                MultipartFile file = files[i];
                //儲存檔案
                saveFile(file);
            }
        }
        json.put("result","success");
        // 返回結果值
        return json;
    }

    private boolean saveFile(MultipartFile file) {
        //判斷檔案是否為空
        if (!file.isEmpty()){
            try {
                //檔案儲存路徑,其中各個函式可以自行百度一下什麼意思,這裡我是儲存到了target/helloworld目錄下新建的images包內
                String filePath = request.getSession().getServletContext().getRealPath("/")+"images\\"+file.getOriginalFilename();
                //轉存檔案
                file.transferTo(new File(filePath));
                return true;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return false;
    }

    //連線前端測試頁面
    @RequestMapping(value = "/file/test",method = RequestMethod.GET)
    public String test(){
        return "fileTest";
    }

這樣就成功實現了把多個圖片檔案匯入到了你的專案中儲存了起來。