springboot文件上传(单文件上传)与下载

1、前端页面

<!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>文件上传下载</title>
</head>
<body>
<form action="http://localhost:8083/fxglxt/testUploadFile" 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="http://localhost:8080/testUploadFiles">
    <p>多文件上传:</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="http://localhost:8083/fxglxt/testDownload">下载</a>
</body>
</html>

  

2、后端上传方法,文件一共有三种上传路径

      1、使用相对路径,文件保存路径为D:/fxglxt/target/classes/static/web/uploadFiles

      2、使用绝对路径,文件上传到D:/fxglxt/src/main/resources/static/web/uploadFiles/文件夹下

   3、使用绝对路径,文件上传到d://uploadFiles/文件夹下

/**
 * 单文件上传
 * @param req
 * @param multiReq
 */
@RequestMapping(value = "/testUploadFile", method = RequestMethod.POST)
public void testUploadFile(HttpServletRequest req,
                           MultipartHttpServletRequest multiReq) {
    // 获取上传文件的路径,uploadFilePath 其实是文件带后缀的名字
    String uploadFilePath = multiReq.getFile("file1").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);
    FileOutputStream fos = null;
    FileInputStream fis = null;
    try {
        //1、使用相对路径
        //获取跟目录,文件保存路径为D:/fxglxt/target/classes/static/web/uploadFiles
       //  File path = new File(ResourceUtils.getURL("classpath:").getPath());
       //  if(!path.exists()) path = new File("");
       //  System.out.println("path:"+path.getAbsolutePath());
       //
       // //如果上传目录为/static/images/upload/,则可以如下获取:
       //  File upload = new File(path.getAbsolutePath(),"static/web/uploadFiles/");
       //  if(!upload.exists()) upload.mkdirs();
       //  System.out.println("upload url:"+upload.getAbsolutePath());
       //
       //
       //  fis = (FileInputStream) multiReq.getFile("file1").getInputStream();
       //  fos = new FileOutputStream(new File(path.getAbsolutePath(),"static/web/uploadFiles/"+ uploadFileName
       //          + ".")
       //          + uploadFileSuffix);
        
        //2、使用绝对路径,文件上传到D:/fxglxt/src/main/resources/static/web/uploadFiles/文件夹下
        String c=System.getProperty("user.dir");
        System.out.println("c"+c);

        fis = (FileInputStream) multiReq.getFile("file1").getInputStream();
        fos = new FileOutputStream(new File(c+"/src/main/resources/static/web/uploadFiles/" + uploadFileName
                + ".")
                + uploadFileSuffix);

        //3、使用绝对路径,文件上传到d://uploadFiles/文件夹下
        // fis = (FileInputStream) multiReq.getFile("file1").getInputStream();
        // fos = new FileOutputStream(new File(c+"d://uploadFiles/" + uploadFileName
        //         + ".")
        //         + uploadFileSuffix);


        System.out.println("fos"+fos);
        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();
            }
        }
    }
}

3、文件的下载

 @RequestMapping(value = "/testDownload", method = RequestMethod.GET)
    public void testDownload(HttpServletResponse res) {
        // String fileName = "列表.txt";
        String path="d://upload/软件工程实训.pdf";
        String fileName=path.substring(path.lastIndexOf("/")+1,path.length());
            System.out.println("fileName="+fileName);
            BufferedInputStream bis = null;
            OutputStream os = null;
            try {
            res.setContentType("application/octet-stream");
            res.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            res.setHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode(fileName, "UTF-8"));
            byte[] buff = new byte[1024];

            os = res.getOutputStream();
            //要下载文件所在的路径以及名称
            bis = new BufferedInputStream(new FileInputStream(new File(path)));
                // bis = new BufferedInputStream(new FileInputStream(new File("d://upload/"
                //         + 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");
    }

  

  

posted @ 2020-06-16 17:23  xuemeng11  阅读(273)  评论(0)    收藏  举报