前言:項目可在文章末尾的百度網盤連接,自取。
前言:本項目基於ssm+maven,使用jdk1.8、tomcat8。
前言:目前項目只有上傳文件這一個功能,實現將指定文件下載到指定位置。後續會擴展,比如將上傳的.xls文件的數據讀出並存到數據庫。
目錄
需求實現-- 上傳文件-- java編碼&.xml配置
一、java編碼
1、接口編碼摘要
1.1、添加spingmvc註解,讓一個java類能夠處理請求
開發處理具體業務邏輯的Handler(@Controller、@Request)。
@Controller:定義類控制器類。
@RequestMapping:處理請求註解。
@Controller
@RequestMapping("/fileService")
public class FileController {}
也就是說,我們寫的接口代碼,是在Spring Web MVC工作流程的第五步和第六步,發揮作用的。
在請求到達後,處理器適配器的作用就是找到請求相應的處理器。
標註了@RequestMapping的每一個方法都可以看成是一個Handler,也就是處理器。
Handler負責具體實際的請求處理。SpringMVC中Handler可以是任意形式,只要能處理請求即可。
1.2、接口的入參和出參
入參file是CommonsMultipartFile類型,並不是基本類型。需要使用@RequestParam註解進行手動映射。
(入參是基本類型的時候,直接聲明形參即可。)
public Result uploadFile(@RequestParam(value = "file") CommonsMultipartFile file) {}
//若去掉@RequestParam(value = "file"),調接口會報500
出參是Result類型,有屬性statusCode、message、data。
2、方法使用
2.1、File類的File(String parent, String child)構造方法
在JDK API 1.6.0中文版官方文檔中,可以找到
大概意思就是,根據目錄創建一個新File實例。
2.2、File類的mkdirs()方法
在JDK API 1.6.0中文版官方文檔中,可以找到
大概意思就是,根據File實例的路徑,在系統磁盤創建目錄。
2.3、CommonsMultipartFile類的transferTo方法
在https://docs.spring.io/spring/docs/4.3.26.RELEASE/javadoc-api/官方文檔裏,可以找到
Transfer the received file to the given destination file,將接收到的文件傳輸到給定的目標文件。
執行transferTo()的語句後,CommonsMultipartFile類對象包含的文件就會傳輸到deat。
例如:
3、接口完整代碼
備註:用到的工具類,可以在文章末尾的網盤資源裏自取,或者改寫。
@RequestMapping(value = "/uploadFile", method = RequestMethod.POST, produces = "application/json")
@ResponseBody
public Result uploadFile(@RequestParam(value = "file") CommonsMultipartFile file) {
logger.info("---------------FileController: uploadFile---------------");
String statusCode = Constants.RESULT_MESSAGE_SUCCESS;
String message = "上傳文件成功";
try {
//得到上傳時的文件名
String uploadName = file.getOriginalFilename();
// 指定上傳文件保存到的文件夾
String filePath = fileUrl + File.separator + CommUtil.getNowDateLongStr("yyyyMMdd");
//指定上傳文件的名字
String fileName = "file_"+ CommUtil.getNowDateLongStr(CommUtil.pattern) + uploadName.substring(uploadName.indexOf("."), uploadName.length());
//創建File對象
File uploadFile = new File(filePath, fileName);
if (!uploadFile.exists()) {
//創建目錄--給定的目標文件
uploadFile.mkdirs();
}
//將接收到的文件傳輸到給定的目標文件
file.transferTo(uploadFile);
} catch (Exception e) {
logger.error("上傳文件異常", e);
statusCode = Constants.RESULT_MESSAGE_ERROR;
message = "文件上傳失敗";
}
return new Result(statusCode, message);
}
二、spingmvc的配置
1、常規配置
用postman測接口,不需要配置視圖解析器,下面這兩個配置就夠了。
<!-- 自動註冊最合適的處理器映射器、處理器適配器 -->
<mvc:annotation-driven />
<!-- 自動掃描,完成bean創建和依賴注入 -->
<context:component-scan base-package="com.sharylala">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service" />
</context:component-scan>
2、配置文件上傳解析器
<!-- 配置文件上傳解析器,id是固定的multipartResovler -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding">
<value>UTF-8</value>
</property>
<property name="maxUploadSize">
<value>32505856</value><!-- 上傳文件大小限制爲31M,31*1024*1024 -->
</property>
<property name="maxInMemorySize">
<value>4096</value>
</property>
</bean>
三、applicationContext的配置
常規配置就行
<!--配置spring包掃描-->
<context:component-scan base-package="com.sharylala"/>
<!--將配置文件中的信息,通過spring加載到容器進行使用-->
<context:property-placeholder ignore-unresolvable="true" location="classpath:config.properties" />
四、web.xml的配置
常規配置就行
<!--spring框架啓動-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--springmvc啓動-->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:/config/springmvc-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!--聲明應用範圍(整個WEB項目)內的上下文初始化參數-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:/config/applicationContext.xml</param-value>
</context-param>
<!--在啓動Web項目時,容器(比如Tomcat)會讀web.xml配置文件中的兩個節點<listener>和<contex-param>-->
五、測試
1、run sharylala
2、postman測接口
3、查看結果和tomcat日誌
完整項目自取
鏈接:https://pan.baidu.com/s/1CCBsfukJgbD1BuyF8Rc6vg
提取碼:hw5s