網(wǎng)站建設(shè)情況的報(bào)告國外引流推廣軟件
Java知識(shí)點(diǎn)總結(jié):想看的可以從這里進(jìn)入
目錄
- 3.6、文件上傳、下載
- 3.6.1、文件上傳
- 3.6.2、文件下載
- 3.7、國際化配置
3.6、文件上傳、下載
3.6.1、文件上傳
form 表單想要具有文件上傳功能,其必須滿足以下 3 個(gè)條件。
- form 表單的 method 屬性必須設(shè)置為 post。
- form 表單的 enctype 屬性設(shè)置為 multipart/form-data。
- 至少提供一個(gè) type 屬性為 file 的 input 輸入框。
在SpringMVC 中為我們提供了文件解析器,來實(shí)現(xiàn)上傳文件的功能,MultipartResolver 本身是一個(gè)接口,我們需要通過它的實(shí)現(xiàn)類來完成對(duì)它的實(shí)例化工作。
實(shí)現(xiàn)類 | 說明 | 依賴 | 支持的 Servlet 版本 |
---|---|---|---|
StandardServletMultipartResolver | Servlet 內(nèi)置的上傳功能。 | 不需要第三方 JAR 包的支持。 | 僅支持 Servlet 3.0 及以上版本 |
CommonsMultipartResolver | 借助 Apache 的 commons-fileupload 來完成具體的上傳操作。 | 需要 Apache 的 commons-fileupload 等 JAR 包的支持。 | 不僅支持 Servlet 3.0 及以上版本,還可以在比較舊的 Servlet 版本中使用。 |
<!-- CommonsMultipartResolver依賴 支持文件上傳(注意此組件在Spring6被移除了)-->
<dependency><groupId>commons-fileupload</groupId><artifactId>commons-fileupload</artifactId><version>1.3.1</version>
</dependency>
<dependency><groupId>commons-io</groupId><artifactId>commons-io</artifactId><version>2.8.0</version>
</dependency>
CommonsMultipartResolver我們?cè)趯W(xué)習(xí)Servlet組件的時(shí)候使用過,它在springMVC中使用時(shí)需要配置文件解析器,其中multipartResolver這個(gè)名字是固定的一旦更改,就無法完成文件的解析和上傳工作。
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"><!--編碼格式 --><property name="defaultEncoding" value="UTF-8"/><!--上傳文件大小--><property name="maxUploadSize" value="103424"/><!-- <property name="maxUploadSizePerFile" value="102400"/>--><property name="resolveLazily" value="true"/>
</bean>
在使用時(shí)直接向Controller的方法中傳入?yún)?shù)即可 MultipartFile file即可使用:
@RequestMapping("")
public void multipartFileTest(MultipartFile file){}
內(nèi)部方法 | 作用 |
---|---|
byte[] getBytes() | 以字節(jié)數(shù)組的形式返回文件的內(nèi)容。 |
String getContentType() | 返回文件的內(nèi)容類型。 |
InputStream getInputStream() | 返回一個(gè) input 流,從中讀取文件的內(nèi)容。 |
String getName() | 返回請(qǐng)求參數(shù)的名稱。 |
String getOriginalFillename() | 返回客戶端提交的原始文件名稱。 |
long getSize() | 返回文件的大小,單位為字節(jié)。 |
boolean isEmpty() | 判斷被上傳文件是否為空。 |
void transferTo(File destination) | 將上傳文件保存到目標(biāo)目錄下。 |
<form th:action="@{/student}" method="post" enctype="multipart/form-data"><table style="margin: auto"><tr><td>照片:</td><td><input type="file" id="chooseImage" name="photos" multiple="multiple" required><br><span id="img-div"></span></td></tr><tr><td colspan="2" align="center"><input type="submit" value="提交"><input type="reset" value="重置"></td></tr></table><!-- 保存用戶自定義的背景圖片 --><img id="preview_photo" src="" width="200px" height="200px">
</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>
<table><tr><td>照片:</td><td th:if="${message}eq'上傳成功'"><img th:src="@{'http://localhost:8080/upload/'+${filename}}" width='200px' height='200px'/><br></td></tr>
</table>

這里有一點(diǎn)要注意,如果使用的eclipse,那么使用request.getSession().getServletContext().getRealPath(“/upload/”),獲取的就是部署到Tomcat的路徑,可以直接獲取,但是如果你使用的是Idea的話,它是把圖片上傳到了target這樣一個(gè)文件夾內(nèi)
如果想獲取這個(gè)路徑的圖片可以通過tomcat設(shè)置一個(gè)虛擬的路徑:
![]()
設(shè)置完成后,通過 http://localhost:8080/虛擬路徑文件夾/文件名,即可獲取上傳的圖片
3.6.2、文件下載
使用ResponseEntity實(shí)現(xiàn)下載文件的功能。
將上面上傳的文件下載:
<tr><td>照片:</td><td th:if="${message}eq'上傳成功'"><img th:src="@{'http://localhost:8080/upload/'+${filename}}" width='200px' height='200px'/><br><a th:href="@{/downLoadFile(fileName=${filename})}">點(diǎn)擊下載</a></td>
</tr>
@RequestMapping("/downLoadFile")
public ResponseEntity<byte[]> downLoadFile(HttpServletRequest request, String fileName) throws IOException {//得到圖片的實(shí)際路徑String realPath = request.getSession().getServletContext().getRealPath("/upload/");realPath = realPath+fileName;//創(chuàng)建該圖片的對(duì)象File file = new File(realPath);//將圖片數(shù)據(jù)讀取到字節(jié)數(shù)組中byte[] bytes = FileUtils.readFileToByteArray(file);//創(chuàng)建 HttpHeaders 對(duì)象設(shè)置響應(yīng)頭信息HttpHeaders httpHeaders = new HttpHeaders();//設(shè)置圖片下載的方式和文件名稱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++) {// 取出字符中的每個(gè)字符char c = str.charAt(i);// Unicode碼值為0~255時(shí),不做處理if (c <= 255) {sb.append(c);} else { // 轉(zhuǎn)換 UTF-8 編碼byte b[];try {b = Character.toString(c).getBytes("UTF-8");} catch (UnsupportedEncodingException e) {e.printStackTrace();b = null;}// 轉(zhuǎn)換為%HH的字符串形式for (int value : b) {int k = value;if (k < 0) {k &= 255;}sb.append("%" + Integer.toHexString(k).toUpperCase());}}}return sb.toString();
}

3.7、國際化配置
國際化(i18n)(internationalization的首末字符i和n,18為中間的字符數(shù))是指軟件開發(fā)時(shí)應(yīng)該具備支持多種語言和地區(qū)的功能。也就是根據(jù)不同國家顯示不同的語言(中國人閱讀為漢語,美國人為英語,韓國人為韓語等等)。
在 Spring 項(xiàng)目中實(shí)現(xiàn)國際化,通常需要以下 4 步:
-
編寫國際化資源文件:文件名格式為:基本名-語言代碼-國家或地區(qū)代碼,例如 messages_zh_CN.properties。
userName=用戶名 password=密碼 welcome=歡迎您 submit=提交 reset=重置userName=userName password=password welcome=Welcome submit=submit reset=reset
寫完之后IDEA會(huì)自動(dòng)歸類這種文件
-
在Spring MVC xml配置文件進(jìn)行配置
<!-- 國際化配置:對(duì)資源文件進(jìn)行綁定 --> <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource"><property name="basename" value="messages"/><property name="defaultEncoding" value="UTF-8"/><property name="cacheSeconds" value="0"/> </bean> <!-- 在界面上進(jìn)行切換,Session --> <bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver"><property name="defaultLocale" value="en_US"/> </bean> <!--用于獲取請(qǐng)求中的國際化信息并將其轉(zhuǎn)換為 Locale 對(duì)象,獲取 LocaleResolver 對(duì)象對(duì)國際化資源文件進(jìn)行解析。--> <mvc:interceptors><bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"><property name="paramName" value="lang"/></bean> </mvc:interceptors>
-
在頁面中獲取國際化內(nèi)容;
<body><h1 th:text="主頁+#{welcome}"></h1><tr><td th:text="#{userName}"></td><td><input type="text" name="userName" required><br></td></tr><tr><td th:text="#{password}"></td><td><input type="password" name="password" required><br></td></tr><tr><td colspan="2" align="center"><input type="submit" th:value="#{submit}"><input type="reset" th:value="#{reset}"></td></tr><a th:href="@{/localeChange(lang=en_US)}">英文</a><a th:href="@{/localeChange(lang=zh_CN)}">中文</a><br/> </body>
-
編寫控制器方法手動(dòng)切換語言。
@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";} }

