pom
commons-logging commons-logging 1.2 org.springframework spring-web 5.3.20 org.springframework spring-webmvc 5.3.20 commons-fileupload commons-fileupload 1.3.3 javax.servlet javax.servlet-api 4.0.1
springmvc.xml: 配置如下
controller
@Controller
public class UploadController {
@RequestMapping("/upload2")
public String fileUpload2(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException {
//上传路径保存设置
String path = request.getServletContext().getRealPath("/upload");
File realPath = new File(path);
if (!realPath.exists()){
realPath.mkdir();
}
System.out.println("上传文件保存地址:"+realPath); //上传文件地址
//修改文件名
String name = file.getOriginalFilename();
String extension = FilenameUtils.getExtension(name);//获取文件的后缀名
String uuid = UUID.randomUUID().toString();//uuid的字符串
String newName = uuid.replace("-","")+"."+extension;
//通过CommonsMultipartFile的方法直接写文件(注意这个时候)
file.transferTo(new File(realPath +"/"+ newName));
return "redirect:/index.jsp";
}
@RequestMapping("download")
public String download(String fileName, HttpServletRequest request, HttpServletResponse response) throws IOException {
//获取下载服务器上文件的绝对路径
String realPath = request.getSession().getServletContext().getRealPath("/upload");
//根据文件名获取服务上指定文件
FileInputStream is = new FileInputStream(new java.io.File(realPath, fileName));
//获取响应对象设置响应头信息 下载的两种形式 inline 在线尝试下载 ,attachment:附件形式下载
//response.setHeader("content-disposition","inline;fileName="+ URLEncoder.encode(fileName,"UTF-8"));
response.setHeader("content-disposition","attachment;fileName="+ URLEncoder.encode(fileName,"UTF-8"));
ServletOutputStream os = response.getOutputStream();
IOUtils.copy(is,os);
IOUtils.closeQuietly(is);
IOUtils.closeQuietly(os);
return null;
}
}
jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
Title
<%--
application/x-www=form-urlencoded:默认方式,只处理表单域中的 value 属性值,采用这种编码方式的表单会将表单域中的值处理成 URL 编码方式。
multipart/form-data:这种编码方式会以二进制流的方式来处理表单数据,这种编码方式会把文件域指定文件的内容也封装到请求参数中,不会对字符编码。
text/plain:除了把空格转换为 “+” 号外,其他字符都不做编码处理,这种方式适用直接通过表单发送邮件。
--%>
下载1.jpg图片
下载excel中文名图片



