在SpringMVC框架中实现文件上传和下载

Posted 十木禾

tags:

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

首先在springmvc.xml中配置文件上传的属性

	<!-- 文件上传的属性值 -->
	 <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding" value="utf-8"></property>
        <property name="maxUploadSize" value="10485760000"></property>
        <property name="maxInMemorySize" value="40960"></property>
        <property name="uploadTempDir" value="/WEB-INF/tmp"></property>
   </bean>

pom.xml文件中加入上传组件的jar

        <!--文件上传-->
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.1</version>
        </dependency>

这两个xml文件配置完成之后,我们就可以开始来写我们的前端页面和后端的控制器代码了。


我们知道后台接受的类是MultipartFile,我们首先来封装一个文件上传的工具类,将文件上传到系统的指定目录下

package com.test.utils;

import com.test.helper.BaseHelper;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;

/**
 * 文件上传工具类.
 *
 * @author 张俊强~.
 * @date 2017/11/15-17:27.
 */
public class FileUploadUtils 

    //目前文件上传的路径
    public static final String tmpFilePath="F:\\\\temp\\\\";

    public static BaseHelper uploadFile(MultipartFile file)

        BaseHelper baseHelper=new BaseHelper();
        if (!file.isEmpty()) 

            String fileName=file.getOriginalFilename();

            try 
                byte[] bytes = file.getBytes();
                BufferedOutputStream stream =
                        new BufferedOutputStream(new FileOutputStream(new File(FileUploadUtils.tmpFilePath+fileName)));
                stream.write(bytes);
                stream.close();
             catch (Exception e) 
                e.printStackTrace();
                baseHelper.setCode(StatusInfoUtils.FAILCODE);
                baseHelper.setMsg(StatusInfoUtils.UPLOADFAIL);
            
         else 
            baseHelper.setCode(StatusInfoUtils.FAILCODE);
            baseHelper.setMsg(StatusInfoUtils.NOFILEFOUND);
        
        return  baseHelper;
    




上面的代码就可以实现文件的保存了。
下面我们来看看单文件上传多文件上传的功能如何实现吧!

单文件上传

前台表单代码

<%----------------单文件上传-----------------%>
<form method="POST" enctype="multipart/form-data" action="fileOperation/fileUpload">
    选择文件: <input type="file" name="file"><br/>
    <input type="submit" value="上传">
</form>

后台业务处理代码

    /**
     * 单文件的上传.
     *
     * @param  file 待上传的文件
     * @return 文件上传的返回信息
     */
    @ResponseBody
    @RequestMapping(value = "fileUpload")
    public BaseHelper fileUploadOperation(@RequestParam("file") MultipartFile file) 

        BaseHelper baseHelper= FileUploadUtils.uploadFile(file);
        return baseHelper;
    

多文件上传

前台表单代码

<%------------多文件上传--------------%>
<form method="POST" enctype="multipart/form-data" action="fileOperation/mulFileUpload">
    <p>
        选择文件:<input type="file" name="files">
    <p>
        选择文件:<input type="file" name="files">
    <p>
        选择文件:<input type="file" name="files">
    <p>
        <input type="submit" value="上传">
</form>

后台处理代码

    /**
     * 多文件的上传.
     *
     * @param  files 待上传的文件组
     * @return 文件上传的返回信息
     */
    @ResponseBody
    @RequestMapping(value = "mulFileUpload")
    public BaseHelper mulFileUploadOperation(@RequestParam("files") MultipartFile[] files) 

        BaseHelper baseHelper=new BaseHelper();
        if (files.length>0) 
            for(MultipartFile file:files)
                baseHelper=FileUploadUtils.uploadFile(file);
            
         else 
            baseHelper.setCode(StatusInfoUtils.FAILCODE);
            baseHelper.setMsg(StatusInfoUtils.NOFILEFOUND);
        
        return  baseHelper;
    

以上就是有关文件上传的功能的实现了,其中的BaseHelperStatusInfoUtils的工具类代码如下

BaseHelper代码

package com.test.helper;

/**
 * 一些基本的返回的信息状态.
 *
 * @author 张俊强~.
 * @date 2017/11/12-10:14.
 */
public class BaseHelper 

    public String getCode() 
        return code;
    

    public void setCode(String code) 
        this.code = code;
    

    public String getMsg() 
        return msg;
    

    public void setMsg(String msg) 
        this.msg = msg;
    

    private String code="SUCCESS";  //默认是成功

    @Override
    public String toString() 
        return "BaseHelper" +
                "code='" + code + '\\'' +
                ", msg='" + msg + '\\'' +
                '';
    

    private String msg="操作成功";   //默认是操作成功


StatusInfoUtils的工具类代码

package com.test.utils;

/**
 * 一些状态信息的静态类.
 *
 * @author 张俊强~.
 * @date 2017/11/12-10:25.
 */
public final class StatusInfoUtils 
    private StatusInfoUtils()//增强其不可实例化的能力 最好再私有构造器类抛异常
    //返回状态信息
    public static final String SUCCESSCODE="SUCCESS";
    public static final String SUCCESSMSG="操作成功";
    public static final String FAILCODE="FAIL";
    public static final String FAILMSG="操作失败";
	//文件上传状态信息
    public static final String UPLOADSUCCESS="上传成功";
    public static final String UPLOADFAIL="上传失败";
    public static final String NOFILEFOUND="未选择文件";


关于文件下载,有两种方法,一种是通过OutputStream写出字节,还有一种是通过PrintWriter 写出字符。

通过OutputStream写出字节

    /**
     * Download file by output stream.
     *
     * @param response the response
     * @param realPath the real path
     * @throws FileNotFoundException the file not found exception
     * @throws IOException           the io exception
     */
    public static void downloadFileByOutputStream(HttpServletResponse response, String realPath)
            throws FileNotFoundException, IOException 
        String fileName = realPath.substring(realPath.lastIndexOf("\\\\") + 1);
        response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        response.setHeader("Content-Type","application/octet-stream");
        response.setHeader("Accept-Ranges","bytes");
        InputStream in = new FileInputStream(realPath);
        int len = 0;
        byte[] buffer = new byte[1024];
        OutputStream out = response.getOutputStream();
        //将FileInputStream流写入到buffer缓冲区
        while ((len = in.read(buffer)) > 0) 
            //使用OutputStream将缓冲区的数据输出到客户端浏览器
            out.write(buffer, 0, len);
        
        in.close();
    

通过PrintWriter 写出字符

    /**
     * Download file by print writer.
     *
     * @param response the response
     * @param realPath the real path
     * @throws FileNotFoundException the file not found exception
     * @throws IOException           the io exception
     */
    public static void downloadFileByPrintWriter(HttpServletResponse response, String realPath)
            throws FileNotFoundException, IOException 
        String fileName = realPath.substring(realPath.lastIndexOf("\\\\") + 1);

        response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        FileReader in = new FileReader(realPath);
        int len = 0;
        char[] buffer = new char[1024];
        PrintWriter out = response.getWriter();//获取PrintWriter输出流
        while ((len = in.read(buffer)) > 0) 
            out.write(buffer, 0, len);//将缓冲区的数据输出到客户端浏览器
        
        in.close();
    

以上 2017-11-15 22:29 于上海
更新时间:2017-11-25 16:49 添加文件下载代码

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

百度WebUploader中实现文件上传下载的三种解决方案(推荐)

JavaWeb中实现文件上传的方式有哪些?

问题:JavaWeb中实现文件上传的方式有哪些?

前端中实现文件上传下载的三种解决方案(推荐)

vue中实现文件上传下载的三种解决方案(推荐)

SpringMVC上传下载