//第一步:导入依赖jar包
<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.4</version>
</dependency>
//编写jsp页面发送上传请求
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h3>文件上传</h3>
<%--<a href="user/fileUpload1">文件上传1</a>--%>
<form action="user/fileUpload1" method="post" enctype="multipart/form-data" >
选择文件:<input type="file" name="upload"/><br/>
<input type="submit" value="上传">
</form>
</body>
</html>
//编写后台上传方法
package com.hope.controller;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.List;
import java.util.UUID;
/**
* @author newcityman
* @date 2019/11/28 - 13:04
*/
@Controller("userController")
@RequestMapping(path = "/user")
public class UserController {
@RequestMapping(path = "/fileUpload1")
public String fileUpload1(HttpServletRequest request) throws Exception {
System.out.println("文件上传。。。。");
//使用fileupload组件完成文件上传
//获取上传的位置
String path = request.getSession().getServletContext().getRealPath("/uploads/");
//判断,路径是否存在
File file = new File(path);
if(!file.exists()){
//创建该文件夹
file.mkdirs();
}
//解析request对象,获取上传文件项
DiskFileItemFactory factory = new DiskFileItemFactory(); //磁盘文件项工厂
ServletFileUpload upload = new ServletFileUpload(factory);
//解析rquest
List<FileItem> items = upload.parseRequest(request);
for(FileItem item:items){
//判断当前文件是否是上传文件项
if(item.isFormField()){
//说明文件是普通文件项
}else{
//说明是上传文件项
//获取上传文件的名称
String fileName = item.getName();
String uuid = UUID.randomUUID().toString().replace("-","");
fileName=uuid+fileName;
//完成文件上传
item.write(new File(path,fileName));
//删除临时文件
item.delete();
}
}
return "success";
}
}