• springMvc06 JSON与文件上传下载


    1、Json

    JSON是当前前后端分开开发传递数据首选的数据格式。

    这里使用jackson开源包实现JSON数据解析转换。

    1.1、导入所需要的包

            <!--JSON数据转换-->
            <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
            <dependency>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-core</artifactId>
                <version>2.12.2</version>
            </dependency>
            <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
            <dependency>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-databind</artifactId>
                <version>2.12.2</version>
            </dependency>
            <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations -->
            <dependency>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-annotations</artifactId>
                <version>2.12.2</version>
            </dependency>
    

    1.2、两个注解

    @RequestBody

    主要用来接收前端传递给后端的json字符串中的数据的(请求体中的数据的);

    必须是Post请求,该注解用在方法的形参上。

    当请求头的ContentType类型是application/json,application/xml等格式的数据时,需要使用该标注。

    能够把json内部包含的变量绑定给对象的包含的属性上。

    @ResponseBody

    用于返回JSON数据,该注解用在方法上,用来把方法返回的对象自动转为JSON格式并返回给前端。

    1.3、测试例子

    代码:

    package rui.web;
    
    import com.fasterxml.jackson.databind.ObjectMapper;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestBody;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.ResponseBody;
    import rui.db.Model.User;
    
    import javax.servlet.http.HttpServletResponse;
    import java.util.Arrays;
    
    @Controller
    @RequestMapping(value = "/json")
    public class jsonController {
    
        //提交Json数据
        @ResponseBody
        @RequestMapping(value = "put")
        public void showInfo(
                HttpServletResponse response,
                @RequestBody User user) throws Exception {
            System.out.println("提交JSON数据");
            System.out.println(user.toString());
    
            ObjectMapper jsonTool = new ObjectMapper();
            response.getWriter().write(jsonTool.writeValueAsString(user));
        }
    
        //返回Json数据
        @ResponseBody
        @RequestMapping(value = "get")
        public User showInfo() {
            User u = new User();
            u.setLoginId("001");
            u.setUserName("王");
            u.setSex("F");
            u.setTelephone("123456789");
            u.setDepartmentId("D01");
            u.setLoves(Arrays.asList("足球", "篮球"));
            return  u;
        }
    }
    

    请求测试-请求:

    请求测试-提交:用Postman

    在Header中增加Content-Type   application/json

    数据输出:

    2、文件上传与下载

    2.1、导入包

            <!--文件上传-->
            <!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
            <dependency>
                <groupId>commons-fileupload</groupId>
                <artifactId>commons-fileupload</artifactId>
                <version>1.4</version>
            </dependency>
            <!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
            <dependency>
                <groupId>commons-io</groupId>
                <artifactId>commons-io</artifactId>
                <version>2.11.0</version>
            </dependency>

    2.2、SpringMVC配置文件添加如下配置

        <!--文件上传配置-->
        <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
            <!--默认编码-->
            <property name="defaultEncoding" value="UTF-8" />
            <!--最大上传200M-->
            <property name="maxUploadSize" value="209715200" />
            <!--推迟文件解析-->
            <property name="resolveLazily" value="true" />
            <!--临时保存路径-->
            <property name="uploadTempDir" value="uploadFiles/temp" />
        </bean>

    2.3、文件上传

    前端通过 input表单上传,允许文件多选

    <div>头像:<input type="file" name="headImgUpload" multiple="multiple" /></div>
    

    form标记需要增加:  enctype="multipart/form-data" 属性。

    保存文件的代码:

    参数名需要和input表单的name属性保持一致,否则无法进行参数绑定。

        //用户注册提交
        @RequestMapping(value = "register", method = RequestMethod.POST)
        public String register(Model model,User user,
                               List<MultipartFile> headImgUpload,
                               HttpServletRequest request) {
            System.out.println("执行TestController==2");
    
            //文件上传保存
            if (headImgUpload != null) {
                for (MultipartFile headImg:headImgUpload) {
    
                    String realPath = request.getServletContext().getRealPath("uploadFiles");
                    System.out.println(realPath);
                    File file = new File(realPath);
                    //不存在,则创建目录
                    if (file.exists() == false)
                        file.mkdir();
                    
                    if (headImg.getSize() > 0) {
                        //获取上传文件名
                        String fileName = headImg.getOriginalFilename();
                        System.out.println(fileName);
                        System.out.println(headImg.getContentType());
                        System.out.println(headImg.getSize());
                        File target = new File(realPath, fileName);
                        try {
                            //保存文件
                            headImg.transferTo(target);
                        } catch (Exception e) {
                            System.out.println("上传失败");
                            e.printStackTrace();
                        }
                    }
                }
            }
            model.addAttribute("user", user);
            return "forward:/test/showInfo";
        }

    2.4、文件下载

        //文件下载
        @RequestMapping(value="download")
        public ResponseEntity<byte[]> downloadFile(String fileName,
                                                   HttpServletRequest request,
                                                   HttpServletResponse response) throws Exception
        {
            String downLoadPath = request.getServletContext().getRealPath("downloadFiles");
            System.out.println(downLoadPath);
            File downFile = new File(downLoadPath+File.separator+fileName);
            if(downFile.exists())
            {
                HttpHeaders headers=new HttpHeaders();
                //解决中文乱码
                String downFileName = new String(downFile.getName().getBytes("utf-8"),"iso-8859-1");
                headers.setContentDispositionFormData("attachment",downFileName);
                //设置要下载文件的MIME类型,这句话可以省略
                headers.setContentType("文件的MIME类型");
                byte[] buffer = FileUtils.readFileToByteArray(downFile);
                ResponseEntity<byte[]> entity=new ResponseEntity<byte[]>(buffer,headers, HttpStatus.OK);
                return entity;
            }
            return null;
        }

    运行测试:

    在浏览器中输入:

    项目中,文件路径一般都保存在数据库中,通过传入要下载的文件的数据库记录主键,通过查询数据库来获取其它相关的信息。

  • 相关阅读:
    HDU 4565 So Easy!(公式化简+矩阵)
    CentOS 64位下安装Postfix+Dovecot 配置邮件server笔记
    TreeView 高速单击时不运行AfterCheck时间
    小强的HTML5移动开发之路(19)——HTML5 Local Storage(本地存储)
    小强的HTML5移动开发之路(18)——HTML5地理定位
    小强的HTML5移动开发之路(17)——HTML5内联SVG
    小强的HTML5移动开发之路(16)——神奇的拖放功能
    小强的HTML5移动开发之路(15)——HTML5中的音频
    小强的HTML5移动开发之路(14)——Video标签详解
    小强的HTML5移动开发之路(13)——HTML5中的全局属性
  • 原文地址:https://www.cnblogs.com/feihusurfer/p/15887118.html
Copyright © 2020-2023  润新知