SpringMVC--03(文件上传与国际化)

1.SpringMVC文件上传

  SpringMVC的文件上传非常的简单,它直接提供了直接的支持,这种支持是通过即插即用的MultipartResolver接口实现的。Spring用它的实现类CommonsMultipartResolver来实现。SpringMVC上下文中没有自动装配所以需要我们手动来配置。我们这里就直接实现一个多文件上传,

 1.前端页面,

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"/>
    <title>主页</title>

</head>
<body>
<form action="/uploadfile" method="post" enctype="multipart/form-data">
    <input type="file" name="file"/></br>
    <input type="file" name="file"/></br>
    <input type="file" name="file"/></br>
    <button type="submit">上传</button>
</form>


</body>
</html>

 2.导入依赖,thymeleaf的核心依赖要大于3

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

3.SpringMVC配置

<!-- 配置文件上传 -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 指定默认的编码格式 -->
        <property name="defaultEncoding" value="UTF-8" />
        <!-- 指定允许上传的文件大小,单位Byte -->
        <property name="maxUploadSize" value="5120000000000" />
    </bean>

4.接收文件,上传文件

/**
     * 单文件上传 :  MultipartFile file
     * 多文件上传 :  @RequestParam("file") MultipartFile[] file
     * 多文件上传必须加上 @RequestParam("file")注解否则会报错
     */
    @RequestMapping(value = "uploadfile", method = RequestMethod.POST)
    public String testFileUpload(HttpServletRequest request, @RequestParam("file") MultipartFile[] file) {
        for (int i = 0; i < file.length; i++) {
            MultipartFile multipartFile = file[i];
            System.out.println(" ContentType: " + multipartFile.getContentType());
            System.out.println(" Name: " + multipartFile.getName());
            System.out.println(" OriginalFilename: " + multipartFile.getOriginalFilename());
            System.out.println(" Size: " + multipartFile.getSize());
            //判断是否提交文件,如果没有那么跳过上传
            if (multipartFile.isEmpty()) {
                //跳出本次循环执行下一次循环
                continue;
            }
            // 获取文件的上传路径
            String uploadpath = request.getServletContext().getRealPath("uploads");
            //String property = System.getProperty("user.dir");
            //获取文件名称
            String filename = multipartFile.getOriginalFilename();
            //截取文件后缀
            String fileext = filename.substring(filename.lastIndexOf("."));
            //生成新的随机文件名称
            String newfileName = UUID.randomUUID() + fileext;

            //文件保存位置
            File saveDir = new File(uploadpath);
            if (!saveDir.exists()) {
                saveDir.mkdir();
            }
            //文件保存路径
            File savepath = new File(uploadpath + "/" + newfileName);
            System.out.println(savepath);
            //上传文件
            try {
                multipartFile.transferTo(savepath);
            } catch (IllegalStateException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "upload";
    }

 2.Spring文件的下载

  利用springmvc提供的ResponseEntity类型,使用它可以很方便地定义返回的HttpHeaders和HttpStatus。

  html页面:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"/>
    <title>主页</title>

</head>
<body>
<form action="/uploadfile" method="post" enctype="multipart/form-data">
    <input type="file" name="file"/></br>
    <input type="file" name="file"/></br>
    <input type="file" name="file"/></br>
    <button type="submit">上传</button>
</form>

<h3><a href="/fileDownLoad">Nutch入门.pdf</a></h3>
</body>
</html>

  2.使用SpringMVC提供的ResponseEntity来实现文件的下载

/***
     * 文件的下载
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("/fileDownLoad")
    public ResponseEntity<byte[]> fileDownLoad(HttpServletRequest request) throws Exception{

        ServletContext servletContext = request.getServletContext();
        String fileName="Nutch入门.pdf";
        String realPath = servletContext.getRealPath("/uploads/"+fileName);//得到文件所在位置
        InputStream in=new FileInputStream(new File(realPath));//将该文件加入到输入流之中
        byte[] body=null;
        body=new byte[in.available()];// 返回下一次对此输入流调用的方法可以不受阻塞地从此输入流读取(或跳过)的估计剩余字节数
        in.read(body);//读入到输入流里面

        fileName=new String(fileName.getBytes("gbk"),"iso8859-1");//防止中文乱码
        HttpHeaders headers=new HttpHeaders();//设置响应头
        headers.add("Content-Disposition", "attachment;filename="+fileName);
        HttpStatus statusCode = HttpStatus.OK;//设置响应吗
        ResponseEntity<byte[]> response=new ResponseEntity<byte[]>(body, headers, statusCode);
        return response;
    }

测试:

3.SpringMVC的国际化

idea配置:

国际化 ,英文叫 internationalization 单词太长 ,又被简称为 i18n(取头取尾中间有18个字母),主要涉及3个类: Locale用来设置定制的语言和国家代码 ,ResourceBundle 用来加载国际化资源文件,MessageFormat 用来格式化占位符。在创建国际化资源文件时,如我在resources文件下建了一个i18n文件夹,下放了3个资源文件,idea自动会生成一个Resource Bundle 'messages'文件夹,这个文件夹不是真实存在的,打开项目所在文件夹后,找不到它的。

创建配置文件:

message_en_US.properties:

loginname = Login name:
password = Password:
submit = Submit
welcome = Welcome {0} to here
title = Login Page
username = administrator

message_zh_CN.properties:

loginname = 登录名:
password = 密码:
submit = 提交
welcome = 欢迎 {0} 来到这里
title = 登录页面
username = 管理员

 

对Spring配置文件中添加国际化bean配置:

<!-- 国际化 -->
    <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
        <property name="basenames" value="i18n.message"></property>
    </bean>

    <!-- 国际化操作拦截器如果采用基于(session/cookie)则必须配置 -->
    <mvc:interceptors>
        <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"></bean>
    </mvc:interceptors>


    <!-- 配置LocalResolver用来获取本地化语言 -->
    <bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver"></bean>
    <!-- 配置LocaleChanceInterceptor拦截器 -->
    <mvc:interceptors>
        <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"/>
    </mvc:interceptors>

 前端:

<!DOCTYPE html>
<html lang="en"  xmlns:th="http://www.thymeleaf.org">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="">
    <title>Signin Template for Bootstrap</title>
    <!-- Bootstrap core CSS -->
   <!-- <link href="asserts/css/bootstrap.min.css" th:href="@{/webjars/bootstrap/4.0.0/css/bootstrap.css}" rel="stylesheet">-->
    <!-- Custom styles for this template -->
    <link href="asserts/css/signin.css" th:href="@{/asserts/css/signin.css}" rel="stylesheet">
    <link rel="stylesheet" href="../static/js/bootstrap/css/bootstrap.min.css">
</head>

<body class="text-center">
<form class="form-signin" action="dashboard.html">
   <!-- <img class="mb-4" th:src="@{/asserts/img/bootstrap-solid.svg}" src="asserts/img/bootstrap-solid.svg" alt="" width="72" height="72">-->
    <h1 class="h3 mb-3 font-weight-normal" th:text="#{title}">Please sign in</h1>
    <label class="sr-only" th:text="#{loginname}">Username</label>
    <input type="text" class="form-control" placeholder="Username" th:placeholder="#{loginname}" required="" autofocus="">
    <label class="sr-only" th:text="#{password}">Password</label>
    <input type="password" class="form-control" placeholder="Password" th:placeholder="#{password}" required="">
    <div class="checkbox mb-3">
        <label>
            <input type="checkbox" value="remember-me"/> [[#{submit}]]
        </label>
    </div>
    <button class="btn btn-lg btn-primary btn-block" type="submit" th:text="#{submit}">Sign in</button>
    <p class="mt-5 mb-3 text-muted">© 2017-2018</p>
    <a class="btn btn-sm" href="hello?locale=zh_CN">中文</a>
    <a  class="btn btn-sm" href="hello?locale=en_US">英文</a>

</form>

</body>

</html>

 每次页面跳转需要加载资源:

package com.wx.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.Locale;
import java.util.Map;

@Controller
public class InternationalizeController {
    @Autowired
    private MessageSource messageSource;

    /**
     * 在跳转页面的时候需要加载国际化资源
     * @param locale
     * @param map
     * @return
     */
    @RequestMapping("/hello")
    public String index(Locale locale, Map<String ,Object> map) {
        String name = messageSource.getMessage("loginname", null, locale);
        String pass = messageSource.getMessage("password", null, locale);
        String submit = messageSource.getMessage("submit", null, locale);
        String welcome = messageSource.getMessage("welcome", null, locale);
        String title = messageSource.getMessage("title", null, locale);

        map.put("loginname", title);
        map.put("password", pass);
        map.put("submit", name);
        map.put("welcome", submit);
        map.put("title", submit);
        /*map.put("user", new User());*/

        return "hello";
    }

}

 测试:

 

 

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

时空恋旅人

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值