java檔案上傳與下載

來源:互聯網
上載者:User

標籤:span   byte   ack   tor   lock   finally   cat   tee   download   

不多說,直接上執行個體代碼!!!

我使用的是idea工具,maven管理。

首先,在pom.xml引入上傳檔案所需要的包。

<!--fileupload-->    <dependency>      <groupId>commons-fileupload</groupId>      <artifactId>commons-fileupload</artifactId>      <version>1.3.1</version>    </dependency>    <dependency>      <groupId>commons-io</groupId>      <artifactId>commons-io</artifactId>      <version>2.2</version>    </dependency>

 

單檔案上傳:

/** * Created by 陳 on 2017/9/17. */@Controller@RequestMapping("/home")public class UploadController {    @RequestMapping("/oneUpload")    public String upload(@RequestParam("file") MultipartFile file, HttpServletRequest request){        String uploadUrl = request.getSession().getServletContext().getRealPath("/") + "upload/";        String filename = file.getOriginalFilename();        //判斷相應路徑是否存在,不存在則建立        File dir = new File(uploadUrl);        if(!dir.exists()){            dir.mkdir();        }        System.out.println("檔案上傳到:" + uploadUrl + filename);        File targetFile = new File(uploadUrl + filename);        if(!targetFile.exists()){            try {                targetFile.createNewFile();            } catch (IOException e) {                e.printStackTrace();            }        }        //移動上傳檔案        try {            file.transferTo(targetFile);        } catch (IOException e) {            e.printStackTrace();        }        System.out.println("http://127.0.0.1:8080/study2/upload/" + filename);        return null;    }
}

 

多檔案上傳:

 @RequestMapping("/moreUpload")    public String moreUpload(HttpServletRequest request){        MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;        Map<String, MultipartFile> files = multipartHttpServletRequest.getFileMap();        String uploadUrl = request.getSession().getServletContext().getRealPath("/") + "upload/";        //判斷相應路徑是否存在,不存在則建立        File dir = new File(uploadUrl);        if(!dir.exists()){            dir.mkdir();        }        List<String> fileList = new ArrayList<String>();        for(MultipartFile file : files.values()){            File targetFile = new File(uploadUrl + file.getOriginalFilename());            if(!targetFile.exists()){                try {                    targetFile.createNewFile();                } catch (IOException e) {                    // TODO Auto-generated catch block                    e.printStackTrace();                }                try {                    file.transferTo(targetFile);                    fileList.add("http://localhost:8080/study2/upload/" + file.getOriginalFilename());                } catch (IllegalStateException e) {                    // TODO Auto-generated catch block                    e.printStackTrace();                } catch (IOException e) {                    // TODO Auto-generated catch block                    e.printStackTrace();                }            }        }        request.setAttribute("files",fileList);        System.out.println(files.size());        return null;    }

 

檔案下載:

@Controllerpublic class downLoadController {    @RequestMapping("/downLoad")    public String downLoad(String fileName, HttpServletRequest request, HttpServletResponse response){        response.setContentType("text/html;charset=utf-8");        try {            request.setCharacterEncoding("UTF-8");        } catch (UnsupportedEncodingException e) {            e.printStackTrace();        }        BufferedInputStream bis = null;        BufferedOutputStream bos = null;        String ctxPath = request.getSession().getServletContext().getRealPath("/") + "upload/";        String downLoadPath = ctxPath + fileName;        System.out.println(downLoadPath);        try {            long fileLength = new java.io.File(downLoadPath).length();            response.setContentType("application/x-msdownload;");            response.setHeader("Content-disposition", "attachment; filename=" + new String(fileName.getBytes("utf-8"), "ISO8859-1"));            response.setHeader("Content-Length", String.valueOf(fileLength));            bis = new BufferedInputStream(new FileInputStream(downLoadPath));            bos = new BufferedOutputStream(response.getOutputStream());            byte[] buff = new byte[2048];            int bytesRead;            while ((bytesRead = bis.read(buff, 0, buff.length)) != -1) {                bos.write(buff, 0, bytesRead);            }        }catch (Exception e){            e.printStackTrace();        }finally {            try {                bis.close();            } catch (IOException e) {                e.printStackTrace();            }            try {                bos.close();            } catch (IOException e) {                e.printStackTrace();            }        }        return null;    }}

 

java檔案上傳與下載

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.