springMVC文件上传和下载功能

本文介绍如何在SSM框架中实现文件的上传与下载功能。主要内容包括配置依赖、设置文件大小限制、使用JSP界面进行文件操作及Controller层的具体实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

以下功能框架用的是SSM

备注:上传成功或出错我没有加跳转界面,大家可以自己加一下,我一般debugger一下,然后看上传的路径下有没有我传的文件(图片等格式都可以)

  1.  首先要导入jar包 

<dependency>
   <groupId>commons-io</groupId>
   <artifactId>commons-io</artifactId>
   <version>${commons-io.version}</version>
</dependency>
<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>${commons-fileupload.version}</version>
</dependency>

  2.  配置上传文件默认大小值(springMVC.xml)

 <!-- 配置文件上传,如果没有使用文件上传可以不用配置,当然如果不配,那么配置文件中也不必引入上传组件包 -->  
    <bean id="multipartResolver"    
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">    
        <!-- 默认编码 -->  
        <property name="defaultEncoding" value="utf-8" />    
        <!-- 文件大小最大值 -->  
        <property name="maxUploadSize" value="10485760000" />    
        <!-- 内存中的最大值 -->  
        <property name="maxInMemorySize" value="40960" />    
    </bean>

   

  3.  jsp界面配置,使用form表单提交,注意设置 enctype="multipart/form-data",如下:

   <form action="fileUpload" method="post" enctype="multipart/form-data">
                    选择文件:<input type ="file" name="filename">
                                     <input type="submit" value="提交">
               </form>
               <form action="downLoad" method="get">
                        <input type="submit" value="下载">
               </form>

   4.  通过注解方式到Controller,详见代码(里面有一些是自己测试的,不过代码保证复制可以跑的通,文件路径等设置成你要下载的或上传的本地路径)

  /**
     * 上传文件到本地(包括压缩文件)
     * @param file
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "fileUpload", method = RequestMethod.POST)
    public DataLib uploadHomework( MultipartFile file,String fileUrl,String dataLibId) {
        if(StringUtils.isNotBlank(fileUrl) && StringUtils.isNotBlank(dataLibId)){
            //删除表记录
            dataLibService.deleteDataLibById(dataLibId);
            //编辑或者再次上传文件,应先删除文件,再添加
            File url = new File(fileUrl);
            url.delete();
        }
        File saveZipDirectory =null;
        String newName ="";
        String fileName ="";
        DataLib entity = new DataLib();
        try {
            if (!file.isEmpty()) {
                 fileName = file.getOriginalFilename();
                String suffix =  fileName.substring(fileName.lastIndexOf(".")+1);
                    saveZipDirectory = new File(Global.getConfig(uploadFileUrl));//上传文件真实路径,静态文件配置,读取
                    if (!saveZipDirectory.exists()) {
                        saveZipDirectory.mkdirs();
                    }
                    System.out.println("saveZipDirectory*****Path:" + saveZipDirectory.getAbsolutePath());
                    // 将上传文件保存到目标文件中
                    //定义文件名 uuid
                     newName = getName(fileName);
                    File toFile = new File(saveZipDirectory.getAbsolutePath() + File.separator + newName);
//                    FileCopyUtils.copy(file.getInputStream(), new FileOutputStream(toFile));
                    file.transferTo(toFile);
            }
        } catch (Exception e) {
            entity.setMsg("上传失败");
         return entity;
        }
        // 保存上传文件,记录表
        entity.setId(newName.substring(0,newName.lastIndexOf(".")));
        entity.setCreateUserId(UserUtils.getUser().getId());
        entity.setCreateDate(new Date());
        entity.setAddress((saveZipDirectory.getAbsolutePath() + File.separator + newName).replace("\\", "/"));
        entity.setName(fileName);
        entity.setSize(file.getSize()+"");
        entity.setFileType(file.getContentType());
        entity.setFshIpPort("");
        entity.setFileGroup("");
        entity.setFilePath(newName);
        dataLibSer.insertDataLib(entity);
      entity.setMsg("上传成功");
        return entity;
    }

    /**
     * 下载文件
     * @param request
     * @param response
     */
    @RequestMapping("/downLoad")
    public void downLoad(HttpServletRequest request, HttpServletResponse response) {
        try {
            request.setCharacterEncoding("utf-8");
            response.setCharacterEncoding("utf-8");
            String fileUrl = request.getParameter("fileUrl");
            String url="";
            if(fileUrl!=null&&!"".equals(fileUrl)){
                //message=URLDecoder.decode(imgUrl, "utf-8");
                //修改中文地址乱码问题
                url= new String(fileUrl.getBytes("ISO8859-1"),"UTF-8") ;

            }
            File file = new File(url);
            String fileName = file.getName();
            if (file != null && fileName != null && fileName.trim() != "") {
                try {
                    InputStream fis = new FileInputStream(file);// 读取文件流
                    byte[] buffer = new byte[1024 * 8];// 缓冲池
                    fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
                    response.reset();
                    // 设置头信息
                    response.setHeader("Content-Type", "application/x-download");
                    response.addHeader("Content-Disposition","attachment;filename*=utf-8''" + fileName);
                    response.setContentType("application/octet-stream");
                    // 输出数据
                    OutputStream out = new BufferedOutputStream(response.getOutputStream());
                    int bytes;
                    while ((bytes = fis.read(buffer, 0, buffer.length)) != -1) {
                        out.write(buffer, 0, bytes);
                    }
                    out.close();
                    fis.close();
                } catch (FileNotFoundException e) {
                    throw new Exception("文件未找到!");
                } catch (IOException e) {
                    throw new Exception("取消下载或文件读写异常!");
                }

            }
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
    }
}
/**
 * 上传文件名字变换
 */
public String getName(String myFileName) {
    String newName = IdGen.uuid() + myFileName.substring(myFileName.lastIndexOf("."));
    return newName;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值