♥springMVC实现文件的上传和下载♥

Posted 牛牛最爱喝兽奶

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了♥springMVC实现文件的上传和下载♥相关的知识,希望对你有一定的参考价值。

springMVC实现文件的上传和下载

注意事项:

给大家讲讲实现上传下载功能注意的一些细节问题!在springmvc属于控制层的容器,所以编写的对象一定要交给spring去管理,所有必须加上@Controller注解。当jsp页面请求服务器时携带了变量参数,在controller代码里的函数要定义接收变量的参数,此时一定注意和pojo里对象的参数名一定要对应,或者写一个@RequestParam(“username”)注解,注解里参数代表着你pojo里的类变量参数名。当我们需要jsp页面给浏览器发送数据,通常以?userid=1001,这种形式在地址栏显示出来,但是引入了/1001的表现形式时,需要在方法前加@RequestMapping(“user/userid”),在方法的变量里加@PathVariable (“userid”)。另外一些细节,浏览器之间的跳转不需经过服务的处理,而是属于页面间的响应,所以如果在浏览器实现页面间跳转失败的话,一定要在xml配置文件中加上你跳转的路径如:

<mvc:view-controller path="/" view-name="user"/>

这些才会被springmvc识别到然后放行。通常一般不需要涉及到服务的jsp文件都要进行这样的定义。

实现文件的上传在SpringMVC里总共有两种方式,一种是是自带的,另一种需要导入外包:

<dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.12</version>
            <scope>provided</scope>
        </dependency>

配置文件:

    <bean class="org.springframework.web.multipart.commons.CommonsMultipartResolver" id="multipartResolver">
        <property name="defaultEncoding" value="UTF-8"/>//防止字符编码
        <property name="maxUploadSize" value="5000000"/>//上传最大数据量
    </bean>

Controller控制

@Controller
public class FileUploadController extends HttpServlet 
    private static final Log looger = LogFactory.getLog(FileUploadController.class);
    @RequestMapping("/fleupload")
    public String oneFileUpload(@ModelAttribute FileDomain fileDomain, HttpServletRequest request)
        System.out.println(fileDomain);
        String realpath = request.getServletContext().getRealPath("uploadfiles");//上传路径
        String fileName = fileDomain.getFile().getOriginalFilename();
        File targetFile = new File(realpath, fileName);//定义file文件
        if (!targetFile.exists()) //文件夹是否存在
            targetFile.mkdirs();//不存在则创建
        
        // 上传
        try 
            fileDomain.getFile().transferTo(targetFile);//上传的关键
            looger.info("成功");
         catch (Exception e) 
            e.printStackTrace();
        
        return "showFile";
    

文件接受Pojo

@Repository
@Data
public class FileDomain 
    private String description;
    private MultipartFile file;

jsp文件

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>文件上传</title>
</head>
<body>
<form action="$pageContext.request.contextPath/fleupload"
method="post" enctype="multipart/form-data">
  选择文件:<input type="file" name="file"><br>
  文件描述:<input type="text" name="description"><br>
  <input type="submit" value="提交">
</form>
</body>
</html>

结果:

同时上传多个文件:
jsp文件:

<html>
<head>
    <title>Title</title>
</head>
<body>
<form action="$pageContext.request.contextPath/fileUploads"
      method="post" enctype="multipart/form-data">
    选择文件:<input type="file" name="files"><br>
    文件描述:<input type="text" name="descriptions"><br>
    选择文件:<input type="file" name="files"><br>
    文件描述:<input type="text" name="descriptions"><br>
    选择文件:<input type="file" name="files"><br>
    文件描述:<input type="text" name="descriptions"><br>
    <input type="submit" value="提交">
</form>
</body>
</html>

Controller

@Controller
public class FileUploadmultips extends HttpServlet 
    @RequestMapping("/fileUploads")
    public String setAllFile(FileDomains fileDomains, HttpServletRequest request) throws IOException 
        System.out.println(fileDomains);
         String realPath = request.getServletContext().getRealPath("uploadfiles");
        List<MultipartFile> list = fileDomains.getFiles();
        for(MultipartFile mf:list)
            String filename = mf.getOriginalFilename();
            File targetFile = new File(realPath, filename);
            mf.transferTo(targetFile);
        
        return "showMuti";
    


测试结果:

显示:

文件下载:
Controller文件

@Controller
public class FileDownController extends HttpServlet 
    @RequestMapping("/showDownFiles")
    public String show(HttpServletRequest request, Model model)
        String realPath = request.getServletContext().getRealPath("uploadfiles");
         File dir = new File(realPath);
         File[] files = dir.listFiles();
        ArrayList<String> filename = new ArrayList<>();
        for(File f:files)
            filename.add(f.getName());
        
        model.addAttribute("files",filename);
        return "showDownFiles";
    
    @RequestMapping("/down")
    public String down(@RequestParam String filename, HttpServletRequest request, HttpServletResponse response) throws IOException 
        String aFilePath = null;
        FileInputStream in = null;
        ServletOutputStream out = null;
        aFilePath = request.getServletContext().getRealPath("uploadfiles");
        response.setHeader("Content-Type","application/x-msdownload");
        response.setHeader("Content-Disposition", "attachment; filename="+toUTF8String(filename));
        in = new FileInputStream(aFilePath+"\\\\"+filename);
        out = response.getOutputStream();
        out.flush();
        int aRead = 0;
        byte b[]= new byte[1024];
        while((aRead=in.read(b))!=-1&in!=null)
            out.write(b,0,aRead);
        
        out.flush();
        in.close();
        out.close();
        return null;
    

    private String toUTF8String(String str)
        StringBuffer sb = new StringBuffer();
        int len = str.length();
        for(int i=0;i<len;i++)
            char c = str.charAt(i);
            if(c>=0&&c<=255)
                sb.append(c);
            else
                byte b[];
                try
                    b = Character.toString(c).getBytes("UTF-8");

                catch (UnsupportedEncodingException e)
                    e.printStackTrace();
                    b =null;
                
                for(int j=0;j<b.length;j++)
                    int k=b[j];
                    if(k<0)
                        k&=255;
                    
                    sb.append("%"+Integer.toHexString(k).toUpperCase());
                
            
        
        return sb.toString();
    


jsp文件

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core"  prefix="c" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<c:forEach items="$files" var="filename">
    <a href="$pageContext.request.contextPath /down?filename=$filename">$filename</a><br>
</c:forEach>
</body>
</html>

结果:

以上是关于♥springMVC实现文件的上传和下载♥的主要内容,如果未能解决你的问题,请参考以下文章

♥springMVC实现文件的上传和下载♥

SpringMVC实现文件的上传下载

SpringMVC_[4]文件上传和下载

SpringMVC_[4]文件上传和下载

学习SpringMVC必知必会~springmvc的数据校验表单标签文件上传和下载

SpringMVC实现文件上传