1. 程式人生 > >SpringMVC流式上傳檔案

SpringMVC流式上傳檔案

1.新增jar包

這裡寫圖片描述

2.spring-controller.xml配置:

<!-- 檔案上傳解析器配置以及大小編碼等引數 -->
    <bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding" value="utf-8" />
        <property name="maxUploadSize"
value="10485760000" />
<property name="maxInMemorySize" value="40960" /> </bean>

3.控制層程式碼:

1.單檔案上傳:

@RequestMapping("upload")
    @ResponseBody
    public void upload(@RequestParam("file") CommonsMultipartFile file,HttpSession session)throws Exception {
        System.out.println
("filename------->"+file.getOriginalFilename()); if(!file.isEmpty()){ try { String filename = new Date().getTime()+file.getOriginalFilename(); String realPath = session.getServletContext().getRealPath("/WEB-INF/upload/"); FileOutputStream os = new FileOutputStream(realPath + filename);
InputStream in = file.getInputStream(); int b = 0; while((b=in.read()) != -1){ os.write(b); } os.flush(); os.close(); in.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }

2.多檔案上傳:

@RequestMapping("threeFileupload")
    public String threeFileUpload(
            @RequestParam("file") CommonsMultipartFile files[],
            HttpSession session) {

        List<String> list = new ArrayList<String>();
        // 獲得專案的路徑
        String path = session.getServletContext().getRealPath(
                "/WEB-INF/upload/");
        // 上傳位置
        File f = new File(path);
        if (!f.exists())
            f.mkdirs();
        for (int i = 0; i < files.length; i++) {
            // 獲得原始檔名
            String fileName = files[i].getOriginalFilename();
            System.out.println("原始檔名:" + fileName);
            // 新檔名
            String newFileName = new Date().getTime()
                    + files[i].getOriginalFilename();
            if (!files[i].isEmpty()) {
                try {
                    FileOutputStream fos = new FileOutputStream(path
                            + newFileName);
                    InputStream in = files[i].getInputStream();
                    int b = 0;
                    while ((b = in.read()) != -1) {
                        fos.write(b);
                    }
                    fos.close();
                    in.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            System.out.println("上傳檔案到:" + path + newFileName);
            list.add(path + newFileName);

        }
        HashMap map =new HashMap();
        map.put("content", list);
        map.put("code",200);
        map.put("msg", "OK");
        return Tools.getJson(map);

    }

這樣一個基於框架的簡單的上傳檔案功能就好啦!