今天上午在上课中,介绍了在一台服务器中,使用springMVC上传文件的操作,具体操作步骤有以下五步
2 spring-mvc配置文件
3 配置web.xml
4 页面配置
5 controller代码
详细代码如下:
1 引入依赖
<!--上传服务器-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
2 spring-mvc配置文件
<!--配置文件上传解析器-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!--设置上传文件最大尺寸 5mb-->
<property name="maxUploadSize">
<value>5242800</value>
</property>
3 配置web.xml
<display-name>Archetype Created Web Application</display-name>
<!--编码过滤器-->
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--前端控制器-->
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
4 页面配置
<form action="${pageContext.request.contextPath}/user/upload">
<input tyep="file">
<input type="submit value="上传">
</form>
5 controller代码
package cn.lijun.controller;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;
/**
* @author lijun
* @date 2019/7/11 9:52
*/
@Controller
@RequestMapping("/user")
public class UploaadContorller {
// 接受数据
@RequestMapping("/upload")
public String upload(String username, MultipartFile upload,HttpServletRequest request){
// 1 路径
String realPath = request.getSession().getServletContext().getRealPath("/upload");
File realFile = new File(realPath);
if(!realFile.exists()){
realFile.mkdirs();
}
//2 文件的名称
String uuidNmae = UUID.randomUUID().toString().replace("-", "");//sjdhjk-shfd
// 获取文件的真实名字
String originalFilename = upload.getOriginalFilename();
System.out.println(originalFilename);
// 唯一的名字
String fileNmae = uuidNmae+originalFilename;
System.out.println(fileNmae);
// 文件上传
try {
upload.transferTo(new File(realFile,fileNmae));
} catch (IOException e) {
e.printStackTrace();
}
return "show";
}