文件上传

简介: 文件上传在开发中是用得非常多的,担是也挺简单的,我这里简单介绍一下; 首先是前端也面,无论是HTML还是jsp,上传文件的控件是一个form表单,method=”post”;必须加上enctype="multipart/form-data";Insert t...

文件上传在开发中是用得非常多的,担是也挺简单的,我这里简单介绍一下;
首先是前端也面,无论是HTML还是jsp,上传文件的控件是一个form表单,method=”post”;必须加上enctype="multipart/form-data"

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="${pageContext.request.contextPath }/uploadFile" method="POST" enctype="multipart/form-data">
    <p>单文件上传:</><br/>
    <input type="file" name="file1"/>
    <input type="submit" value = "上传"/>
</form>
<form method="POST" enctype="multipart/form-data" 
    action="${pageContext.request.contextPath }/uploadFiles">
    <p>多文件上传:</>
    <p>文件1:<input type="file" name="file" /></p>
    <p>文件2:<input type="file" name="file" /></p>
    <p><input type="submit" value="上传" /></p>
</form>
<a href="${pageContext.request.contextPath }/download">下载</a>
</body>
</html>

以下是control部分的代码,简单不多做解释:

@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
    public void uploadFile(HttpServletRequest req,
            MultipartHttpServletRequest multiReq) {
        // 获取上传文件的路径
        String uploadFilePath = multiReq.getFile("file1").getOriginalFilename();
        logger.info("uploadFlePath:" + uploadFilePath);
        // 截取上传文件的文件名
        String uploadFileName = uploadFilePath.substring(uploadFilePath.lastIndexOf('\\') + 1,
                uploadFilePath.indexOf('.'));
        logger.info("multiReq.getFile()" + uploadFileName);
        // 截取上传文件的后缀
        String uploadFileSuffix = uploadFilePath.substring(uploadFilePath.indexOf('.') + 1,
                uploadFilePath.length());
        logger.info("uploadFileSuffix:" + uploadFileSuffix);
        FileOutputStream fos = null;
        FileInputStream fis = null;
        try {
            fis = (FileInputStream)multiReq.getFile("file1").getInputStream();
            fos = new FileOutputStream(new File("D:" + File.separator
                    + "picture" + File.separator + uploadFileName + "."
                    + uploadFileSuffix));
            byte[] temp = new byte[1024];
            int i = fis.read(temp);
            while (i != -1) {
                fos.write(temp, 0, temp.length);
                fos.flush();
                i = fis.read(temp);
            }
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            if (fis != null) {
                try {
                    fis.close();
                }
                catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                }
                catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @RequestMapping(value = "uploadFiles", method = RequestMethod.POST)
    @ResponseBody
    public void uploadFiles(HttpServletRequest request) {
        List<MultipartFile> files = ((MultipartHttpServletRequest)request).getFiles("file");
        MultipartFile file = null;
        BufferedOutputStream stream = null;
        for (int i = 0; i < files.size(); ++i) {
            file = files.get(i);
            if (!file.isEmpty()) {
                try {
                    String uploadFilePath = file.getOriginalFilename();
                    System.out.println("uploadFlePath:" + uploadFilePath);
                    // 截取上传文件的文件名
                    String uploadFileName = uploadFilePath.substring(uploadFilePath.lastIndexOf('\\') + 1,
                            uploadFilePath.indexOf('.'));
                    System.out.println("multiReq.getFile()" + uploadFileName);
                    // 截取上传文件的后缀
                    String uploadFileSuffix = uploadFilePath.substring(uploadFilePath.indexOf('.') + 1,
                            uploadFilePath.length());
                    System.out.println("uploadFileSuffix:" + uploadFileSuffix);
                    stream = new BufferedOutputStream(new FileOutputStream(
                            new File("D:" + File.separator + "picture"
                                    + File.separator + uploadFileName + "."
                                    + uploadFileSuffix)));
                    byte[] bytes = file.getBytes();
                    stream.write(bytes, 0, bytes.length);
                }
                catch (Exception e) {
                    e.printStackTrace();
                }
                finally {
                    try {
                        if (stream != null) {
                            stream.close();
                        }
                    }
                    catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            else {
                System.out.println("上传文件为空");
            }
        }
        System.out.println("文件接受成功了");
    }

    @RequestMapping(value = "/download", method = RequestMethod.GET)
    public void download(HttpServletResponse res) {
        String fileName = "info.log";
        res.setHeader("content-type", "application/octet-stream");
        res.setContentType("application/octet-stream");
        res.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        byte[] buff = new byte[1024];
        BufferedInputStream bis = null;
        OutputStream os = null;
        try {
            os = res.getOutputStream();
            bis = new BufferedInputStream(new FileInputStream(new File("D:"
                    + File.separator + "picture" + File.separator + fileName)));
            int i = bis.read(buff);
            while (i != -1) {
                os.write(buff, 0, buff.length);
                os.flush();
                i = bis.read(buff);
            }
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            if (bis != null) {
                try {
                    bis.close();
                }
                catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        System.out.println("success");
    }
目录
相关文章
|
6月前
|
C#
C#文件上传
C#文件上传
28 0
|
7月前
|
JavaScript 前端开发 移动开发
浅谈文件上传
浅谈文件上传
浅谈文件上传
|
6月前
|
存储 移动开发 JavaScript
|
8月前
|
安全 应用服务中间件 PHP
[SUCTF 2019]CheckIn(文件上传)
[SUCTF 2019]CheckIn(文件上传)
66 0
|
10月前
|
前端开发 Java Apache
文件上传与下载
文件上传与下载 文件上传也称为upload,是指将本地图片、视频、音频等文件上传到服务器上,可以供其他用户浏览或下载的过程。文件上传在项目中应用非常广泛,我们经常发微博、发微信朋友圈都用到了文件上传功能。 文件上传时,对页面的form表单有如下要求: method=“post” 采用post方式提交数据 enctype=“multipart/form-data” 采用multipart格式上传文件 type=“file” 使用input的file控件上传
|
11月前
|
开发框架 安全 JavaScript
文件上传利用总结
文件上传利用总结
247 0
|
JavaScript
你真的了解文件上传吗?
你真的了解文件上传吗?
|
数据安全/隐私保护 Windows