java文件上传下载

pom文件:

<!-- 文件上传 -->
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
          </dependency>
          
          <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3</version>
          </dependency>
          
          <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.3.2</version>
          </dependency>

springmvc里面引入配置:

<!-- 定义文件解释器 -->
    <bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 设置默认编码 -->
        <property name="defaultEncoding" value="utf-8"></property>
        <!-- 上传图片最大大小500M -->
        <property name="maxUploadSize" value="524244000"></property>
    </bean>

上传文件的controller:(注:可以通过partFile.getOriginalFilename()来获取文件的后缀,以此来为文件添加新的名字)

 @RequestMapping(value="/upload1",method=RequestMethod.POST)
        @ResponseBody
        //注意上传的时候前台的name属性值要和partFile对应,若不对应怎需要加上@RequestParam("file")注解
        private String upload2(@RequestParam("file")MultipartFile partFile,HttpServletRequest request) {
            try {
                //上传文件的地址:这里是tomcat下的expressproject工程下的image目录
                String path = request.getServletContext().getRealPath("/image");
                //获取文件的原始名
                String filename = partFile.getOriginalFilename();
                //上传文件的地址
                File file = new File(path+"/"+filename);
                InputStream inputStream = partFile.getInputStream();
                //将上传的文件流写入到地址里面
                FileUtils.copyInputStreamToFile(inputStream, file);
                if(inputStream!=null){
                    inputStream.close();
                }
                return "文件上传成功!";
            } catch (Exception e) {
                e.printStackTrace();
                return "文件上传失败!";
            } 
        }

 或者

 @RequestMapping(value="/upload",method=RequestMethod.POST)
    @ResponseBody  
    public String upload(MultipartFile file,HttpServletRequest request) throws IOException{  
        String path = request.getSession().getServletContext().getRealPath("upload");  
        String fileName = file.getOriginalFilename();    
        File dir = new File(path,fileName);//这里可以修改成新的文件名:String newName = UUID.randomUUID().toString().replaceAll("-", "");          
        if(!dir.exists()){  
            dir.mkdirs();  
        }  
        //dir可修改文件名
        file.transferTo(dir);  
        return fileName;  
    } 

下载文件的controller:

   @RequestMapping("/down")
        private void down1(HttpServletRequest request,HttpServletResponse response) throws IOException {
            //下载文件的地址
            String path = request.getServletContext().getRealPath("/image");
            File file = new File(path);
            File[] files = file.listFiles();
            //取第一个文件名
            String name = files[0].getName();
            //防止文件名中文乱码
            name = URLEncoder.encode(name,"UTF-8");
            response.addHeader("content-disposition", "attachment;filename="+name);
            //下载第一个文件
            FileUtils.copyFile(files[0], response.getOutputStream());
        }

前台代码index.jsp:

<%@ 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=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
     <form action="http://localhost:8080/expressproject/upload" method="post" enctype="multipart/form-data">  
        选择文件: <input type="file" name="file" width="120px">  
        <input type="submit" value="上传">  
    </form> 
    <hr>  
    <form action="http://localhost:8080/expressproject/down" method="get">  
        <input type="submit" value="下载">  
    </form> 
</body>
</html>
原文地址:https://www.cnblogs.com/anlegou/p/8883472.html