Uploader:
Controller:
@Controller
public class FileUpload {
@RequestMapping("upload")
//MultipartFile获取表单上传的文件,参数要和表单的name一样
public String demo1(MultipartFile file,String name) throws IOException {
//获取表单的数据
System.out.println(name);
//获取表单上传的文件流
InputStream fileInputStream = file.getInputStream();
//获取上传的文件名,不可以用getName(),因为getName获得的是表单的name
String fileName = file.getOriginalFilename();
//获取上传文件的后缀名
String suffix = fileName.substring(fileName.lastIndexOf("."));
//生成一个不重复的字符串
UUID randomUUID = UUID.randomUUID();
//新建 一个File对象 ,将文件输出到D盘
File outputFile = new File("D:/"+randomUUID.toString()+suffix);
//FileUtils工具类将流输出到文件
FileUtils.copyInputStreamToFile(fileInputStream, outputFile);
return "index.jsp";
}
}
html:
<body>
<form action="upload" enctype="multipart/form-data" method="post" >
name:<input type="text" name="name" />
file:<input type="file" name="file" />
<input type="submit" name="upload" />
</form>
</body>
SpringMVC.xml:
<!-- MultipartResolver解析器 ,如果不配置,会导致获取不到数据-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 上传文件最大为50K -->
<property name="maxUploadSize" value="50"></property>
</bean>
<!-- 异常解析器。如果出现指家的异常,跳转到指定的页面 -->
<bean id="exception" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="org.springframework.web.multipart.MaxUploadSizeExceededException">/error.jsp</prop>
</props>
</property>
</bean>
DownLoad:
Contorller:
@RequestMapping("myDownload")
public void demo1(String fileName,HttpServletRequest request,HttpServletResponse response) throws IOException {
//设置响应头,如果不设置,浏览器会尝试解析文件,如果解析不了,才会提示下载
response.setHeader("Content-Disposition","attachment;filename="+fileName);
//获取字节输出流
ServletOutputStream outputStream = response.getOutputStream();
//获取files文件夹在硬盘的路径
String path = request.getServletContext().getRealPath("files");
//new一个file对象
File file = new File(path,fileName);
System.out.println(file);
//FileUtils工具类,将文件转换为字节数组
byte[] fileBytes = FileUtils.readFileToByteArray(file);
//将字节数组输出到ServletOutputStream中
outputStream.write(fileBytes);
outputStream.flush();
outputStream.close();
}
}
html:
<a href="myDownload?fileName=apache.rar">myDownload</a><br>