使用Spring框架中的CommosMultipartResolver 上传插件制作上传和下载功能

一、文件上传

1、依赖jar

commons-io-2.5.jar 和 commons-fileupload-1.3.1.jar

2、使用前配置

因为该插件是Spring中的插件,使用前我们需要在spring-mvc.xml中做如下配置

<!--文件上传的配置 START -->
	<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<description>配置文件上传</description>
		<property name="defaultEncoding" value="utf-8" />
		<!-- 文件大小最大值 -->
		<property name="maxUploadSize" value="10485760000" />
		<!-- 内存中的最大值 -->
		<property name="maxInMemorySize" value="40960" />
                <!-- 上传的临时目录,感觉也可以不配-->
		<property name="uploadTempDir" value="/WEB-INF/xxx"/>
	</bean>
<!-- 文件上传的配置 END -->

3、在jsp中写一个form表单

<form method="POST" enctype="multipart/form-data" >

    <div>
       <input style="float: left;" type="file"  id="inputPassword4"/>
       <button style="float: right;" type="submit"  @click="fileuploader">上传</button>
    </div>

</form>

//该表单中的点击事件用的是 vue.js  大家也可以使用Jquery中的点击事件写法

4、编写form表单中的上传按钮点击事件的方法fileuploader

// 附件上传
function fileuploader(){
    var _self = this;
    var formData = new FormData();
    if ($("#inputPassword4").val() == null || $("#inputPassword4").val() == "") {
        alert("info", "无附件");
    } else {
       // 获得附件名称
       var filename = $("#inputPassword4").val();
       filename = filename.substring(filename.lastIndexOf("\\") + 1);
        formData.append("file", $("#inputPassword4")[0].files[0]);
        $.ajax({
            url: '/' + window.location.pathname.split('/')[1]+ '/Upload/fileUpload',
            type: 'POST',
            data: formData,
            async: false,
            cache: false,
            contentType: false,
            processData: false,
            success: function (data) {
                  alert("success", "上传成功!");
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                   alert("error", "上传出错!");
            }
              });

            }
      }

5、编写上传的服务接口

@Controller
@RequestMapping("/Upload")
public class FileUploadController {
    @RequestMapping(value = "/fileUpload")
    @ResponseBody
    public String upload(@RequestParam("file") MultipartFile file,
                       HttpServletRequest request) throws IOException {

        String relativepath ="";

        //读取配置文件
        Properties preperties=new Properties();
        preperties.load(FileUploadController.class.getClassLoader().getResourceAsStream("resource.properties"));
        relativepath=preperties.getProperty("path");

        // 判断上传文件不能为空
        if (file != null) {
            // 获得当前上传路径
            String path = request.getServletContext().getRealPath(relativepath) + File.separator + file.getOriginalFilename();
            //  把文件上传指定目录中(transferTo 方法真是太牛逼了),这里MultipartFile 可以是一个集合MultipartFile [] files,多笔上传你懂了吧!
            file.transferTo(new File(path));
        }
        return  "成功";
    }
}

二、文件下载

使用PrintWriter和OutputStream两种方法(他们的区别就是字符流和字节流的区别)

1、PrintWriter

         1.1 使用步骤

  • 设置头信息
  • 通过getWriter()方法获得PrintWriter
  • 开始读写

         1.2 下载代码

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输出流
        PrintWriter out = response.getWriter();
        while ((len = in.read(buffer)) > 0) {
            out.write(buffer, 0, len);//将缓冲区的数据输出到客户端浏览器
        }
        in.close();
    }

2、OutputStream

         2.1 使用步骤

  • 设置头信息
  • 通过getOutputStream()方法获得OutputStream
  • 开始读写
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();
    }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值