SpringMVC中文件的上传

1:首先搭建了一个sprigmvc的环境,在spring的配置文件中添加下面的配置。里面还可以有很多其他的参数。

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 设置上传文件的最大尺寸为5MB -->
        <property name="maxUploadSize" value="5242880"/>
        <property name="defaultEncoding" value="utf-8"/>
    </bean>

前台表单页面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <form enctype="multipart/form-data" action="${pageContext.request.contextPath}/upload" method="post">
        <input type="file" name="file">
        <input type="submit" value="upload">
    </form>
    <hr>
    <form enctype="multipart/form-data" action="${pageContext.request.contextPath}/upload2" method="post">
        <input type="file" name="file">
        <input type="submit" value="upload">
    </form>
</body>
</html>

controller层

package com.dongmu.controller;

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@RestController
public class MyController {
    @RequestMapping("/upload")
    public String upload(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException {
        String name = file.getOriginalFilename();
//注意:String getFieldName():获取表单项的name的属性值。
//        System.out.println("上传文件的全部路径:"+name);
        //获取上传文件的文件名
        if (name!=null&&name.length()>0){
//            String uuidPath= UUID.randomUUID().toString();

            String uploadPath = request.getServletContext().getRealPath("/upload");
            /*File uploadFile = new File(uploadPath);
            if (!uploadFile.exists()){
                uploadFile.mkdir();
            }*/

//            String realPath = uploadPath+"/"+uuidPath;
            File realuploadFile = new File(uploadPath);
            if (!realuploadFile.exists()){
                realuploadFile.mkdirs();
            }


            //获得文件的上传流
            InputStream inputStream = file.getInputStream();
            //获取文件的输出流
            FileOutputStream outputStream = new FileOutputStream(new File(realuploadFile,name));

            //创建一个缓冲区
            byte[] bytes = new byte[1024*1024];

            int len = 0;

            while ((len=inputStream.read(bytes))>0){
                outputStream.write(bytes,0,len);
            }

            outputStream.close();
            inputStream.close();

            System.out.println("文件上传成功");

            return "redirect:/index.jsp";
        }else {
            return "redirect:/index.jsp";
        }
    }

    @RequestMapping("/upload2")
    public String upload2(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException {
        String uploadPath = request.getServletContext().getRealPath("/upload");
        File uploadFile = new File(uploadPath);
        if (!uploadFile.exists()){
            uploadFile.mkdir();
        }
        file.transferTo(new File(uploadFile+"/"+file.getOriginalFilename()));

        return "redirect:/index.jsp";
    }
}

springMVC利用response实现资源的下载

@RequestMapping("/download")
    public void download2(HttpServletRequest request, HttpServletResponse response) throws IOException {
        System.out.println(123);
        String realpath = request.getServletContext().getRealPath("/");
        String filename = "壁纸.jpg";
        System.out.println(realpath);
        response.setHeader("Content-Disposition", "attachment;fileName="+ URLEncoder.encode(filename,"utf-8"));
        FileInputStream inputStream = new FileInputStream(realpath+"static/nsn.jpg");
        response.setContentType("multipart/form-data");
        System.out.println(222);
        byte[] bytes = new byte[1024];
        int len =0;
        //用response对象获取输出流
        ServletOutputStream outputStream = response.getOutputStream();
        while ((len=inputStream.read(bytes))>0){
            outputStream.write(bytes,0,len);
        }
        System.out.println(333);
        inputStream.close();
        outputStream.close();


    }
要保证自己网站下面的资源目录里面有这个资源,不然会出错。

SpringMVC中文件的上传

上一篇:SpringMVC学习笔记06--------乱码问题处理


下一篇:1.26