建设单位发包许可证网站,知名商城网站建设价格低,html 网站,eclipse做企业网站Java知识点总结#xff1a;想看的可以从这里进入 目录3.6、文件上传、下载3.6.1、文件上传3.6.2、文件下载3.7、国际化配置3.6、文件上传、下载
3.6.1、文件上传
form 表单想要具有文件上传功能#xff0c;其必须满足以下 3 个条件。
form 表单的 method 属性必须设置为 p… Java知识点总结想看的可以从这里进入 目录3.6、文件上传、下载3.6.1、文件上传3.6.2、文件下载3.7、国际化配置3.6、文件上传、下载
3.6.1、文件上传
form 表单想要具有文件上传功能其必须满足以下 3 个条件。
form 表单的 method 属性必须设置为 post。form 表单的 enctype 属性设置为 multipart/form-data。至少提供一个 type 属性为 file 的 input 输入框。
在SpringMVC 中为我们提供了文件解析器来实现上传文件的功能MultipartResolver 本身是一个接口我们需要通过它的实现类来完成对它的实例化工作。
实现类说明依赖支持的 Servlet 版本StandardServletMultipartResolverServlet 内置的上传功能。不需要第三方 JAR 包的支持。仅支持 Servlet 3.0 及以上版本CommonsMultipartResolver借助 Apache 的 commons-fileupload 来完成具体的上传操作。需要 Apache 的 commons-fileupload 等 JAR 包的支持。不仅支持 Servlet 3.0 及以上版本还可以在比较旧的 Servlet 版本中使用。
!-- CommonsMultipartResolver依赖 支持文件上传注意此组件在Spring6被移除了--
dependencygroupIdcommons-fileupload/groupIdartifactIdcommons-fileupload/artifactIdversion1.3.1/version
/dependency
dependencygroupIdcommons-io/groupIdartifactIdcommons-io/artifactIdversion2.8.0/version
/dependencyCommonsMultipartResolver我们在学习Servlet组件的时候使用过它在springMVC中使用时需要配置文件解析器其中multipartResolver这个名字是固定的一旦更改就无法完成文件的解析和上传工作。
bean idmultipartResolver classorg.springframework.web.multipart.commons.CommonsMultipartResolver!--编码格式 --property namedefaultEncoding valueUTF-8/!--上传文件大小--property namemaxUploadSize value103424/!-- property namemaxUploadSizePerFile value102400/--property nameresolveLazily valuetrue/
/bean在使用时直接向Controller的方法中传入参数即可 MultipartFile file即可使用
RequestMapping()
public void multipartFileTest(MultipartFile file){}内部方法作用byte[] getBytes()以字节数组的形式返回文件的内容。String getContentType()返回文件的内容类型。InputStream getInputStream()返回一个 input 流从中读取文件的内容。String getName()返回请求参数的名称。String getOriginalFillename()返回客户端提交的原始文件名称。long getSize()返回文件的大小单位为字节。boolean isEmpty()判断被上传文件是否为空。void transferTo(File destination)将上传文件保存到目标目录下。
form th:action{/student} methodpost enctypemultipart/form-datatable stylemargin: autotrtd照片/tdtdinput typefile idchooseImage namephotos multiplemultiple requiredbrspan idimg-div/span/td/trtrtd colspan2 aligncenterinput typesubmit value提交input typereset value重置/td/tr/table!-- 保存用户自定义的背景图片 --img idpreview_photo src width200px height200px
/form使用Controller上传图片
RequestMapping(value /uploadPhoto, method RequestMethod.POST)
public String uploadPhoto(MultipartFile photo, HttpServletRequest request,Model model) {String realPath request.getSession().getServletContext().getRealPath(/upload/);System.out.println(realPath);File fileDir new File(realPath);if (!fileDir.exists()) {fileDir.mkdir();}String filename photo.getOriginalFilename();System.err.println(正在上传的图片为 filename);String newFileName UUID.randomUUID() filename;try {//将文件保存指定目录photo.transferTo(new File(realPath newFileName));model.addAttribute(message,上传成功);model.addAttribute(filename,newFileName);} catch (Exception e) {model.addAttribute(message,上传失败);e.printStackTrace();}return page/success;
}h1 th:text${message}/h1
tabletrtd照片/tdtd th:if${message}eq上传成功img th:src{http://localhost:8080/upload/${filename}} width200px height200px/br/td/tr
/table这里有一点要注意如果使用的eclipse那么使用request.getSession().getServletContext().getRealPath(“/upload/”)获取的就是部署到Tomcat的路径可以直接获取但是如果你使用的是Idea的话它是把图片上传到了target这样一个文件夹内 如果想获取这个路径的图片可以通过tomcat设置一个虚拟的路径 设置完成后通过 http://localhost:8080/虚拟路径文件夹/文件名即可获取上传的图片 3.6.2、文件下载
使用ResponseEntity实现下载文件的功能。
将上面上传的文件下载:
trtd照片/tdtd th:if${message}eq上传成功img th:src{http://localhost:8080/upload/${filename}} width200px height200px/bra th:href{/downLoadFile(fileName${filename})}点击下载/a/td
/trRequestMapping(/downLoadFile)
public ResponseEntitybyte[] downLoadFile(HttpServletRequest request, String fileName) throws IOException {//得到图片的实际路径String realPath request.getSession().getServletContext().getRealPath(/upload/);realPath realPathfileName;//创建该图片的对象File file new File(realPath);//将图片数据读取到字节数组中byte[] bytes FileUtils.readFileToByteArray(file);//创建 HttpHeaders 对象设置响应头信息HttpHeaders httpHeaders new HttpHeaders();//设置图片下载的方式和文件名称httpHeaders.setContentDispositionFormData(attachment, toUTF8String(fileName));httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);return new ResponseEntity(bytes, httpHeaders, HttpStatus.OK);
}public String toUTF8String(String str) {StringBuffer sb new StringBuffer();int len str.length();for (int i 0; i len; i) {// 取出字符中的每个字符char c str.charAt(i);// Unicode码值为0~255时不做处理if (c 255) {sb.append(c);} else { // 转换 UTF-8 编码byte b[];try {b Character.toString(c).getBytes(UTF-8);} catch (UnsupportedEncodingException e) {e.printStackTrace();b null;}// 转换为%HH的字符串形式for (int value : b) {int k value;if (k 0) {k 255;}sb.append(% Integer.toHexString(k).toUpperCase());}}}return sb.toString();
}3.7、国际化配置
国际化i18ninternationalization的首末字符i和n18为中间的字符数是指软件开发时应该具备支持多种语言和地区的功能。也就是根据不同国家显示不同的语言中国人阅读为汉语美国人为英语韩国人为韩语等等。
在 Spring 项目中实现国际化通常需要以下 4 步 编写国际化资源文件:文件名格式为基本名-语言代码-国家或地区代码例如 messages_zh_CN.properties。 userName用户名
password密码
welcome欢迎您
submit提交
reset重置userNameuserName
passwordpassword
welcomeWelcome
submitsubmit
resetreset写完之后IDEA会自动归类这种文件 在Spring MVC xml配置文件进行配置 !-- 国际化配置对资源文件进行绑定 --
bean idmessageSource classorg.springframework.context.support.ResourceBundleMessageSourceproperty namebasename valuemessages/property namedefaultEncoding valueUTF-8/property namecacheSeconds value0/
/bean
!-- 在界面上进行切换Session --
bean idlocaleResolver classorg.springframework.web.servlet.i18n.SessionLocaleResolverproperty namedefaultLocale valueen_US/
/bean
!--用于获取请求中的国际化信息并将其转换为 Locale 对象获取 LocaleResolver 对象对国际化资源文件进行解析。--
mvc:interceptorsbean classorg.springframework.web.servlet.i18n.LocaleChangeInterceptorproperty nameparamName valuelang//bean
/mvc:interceptors在页面中获取国际化内容 bodyh1 th:text主页#{welcome}/h1trtd th:text#{userName}/tdtdinput typetext nameuserName requiredbr/td/trtrtd th:text#{password}/tdtdinput typepassword namepassword requiredbr/td/trtrtd colspan2 aligncenterinput typesubmit th:value#{submit}input typereset th:value#{reset}/td/tra th:href{/localeChange(langen_US)}英文/aa th:href{/localeChange(langzh_CN)}中文/abr/
/body编写控制器方法手动切换语言。 Controller
public class I18nController {Autowiredprivate ResourceBundleMessageSource messageSource;RequestMapping(/localeChange)public String localeChange(Locale locale) {String userName messageSource.getMessage(userName, null, locale);String password messageSource.getMessage(password, null, locale);String submit messageSource.getMessage(submit, null, locale);String reset messageSource.getMessage(reset, null, locale);return index;}
}