一、文件上传
1、设置 form 属性
①.在做文件上传的时候 首先需要再HTML 表单中设置 设置enctype=“multipart/form-data”,
②.只有使用enctype=“multipart/form-data”,表单才会把文件的内容编码到HTML请求中
③.multipart/form-data不对字符编码。在使用包含文件上传控件的表单时,必须使用该值,
所以,只有使用enctype=“multipart/form-data”,表单才会把文件的内容编码到HTML请求中。
2、springmvc配置文件中配置
<!--
配置文件上传 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="104857600" />
<property name="maxInMemorySize" value="4096" />
<property name="defaultEncoding" value="UTF-8"></property>
</bean>
代码如下:
/*
*采用spring提供的上传文件的方法
*/
@RequestMapping("getFile")
public String springUpload(HttpServletRequest request)
throws IllegalStateException, IOException
{
long startTime=System.currentTimeMillis();
//将当前上下文初始化给 CommonsMutipartResolver (多部分解析器)
CommonsMultipartResolver multipartResolver=new CommonsMultipartResolver(
request.getSession().getServletContext());
//检查form中是否有enctype="multipart/form-data"
if(multipartResolver.isMultipart(request))
{
//将request变成多部分request
MultipartHttpServletRequest multiRequest=(MultipartHttpServletRequest)request;
//获取multiRequest 中所有的文件名
Iterator iter=multiRequest.getFileNames();
while(iter.hasNext())
{
//一次遍历所有文件
MultipartFile file=multiRequest.getFile(iter.next().toString());
if(file!=null)
{
String path="H:/testFile/"+file.getOriginalFilename();
//上传
file.transferTo(new File(path));
}
}
}
long endTime=System.currentTimeMillis();
System.out.println("运行时间:"+String.valueOf(endTime-startTime)+"ms");
return "success";
}
<--------------- 前端代码 ------------->
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
<!-- 需要指定 enctype="multipart/form-data-->
<form>
action="${basePath}getFile" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="upload"/>
</form>
二、文件下载
@RequestMapping("download")
public ResponseEntity<byte[]> download(HttpServletRequest request) throws IOException {
File file = new File("H:\\testFile\\LQ.jpeg");
byte[] body = null;
InputStream is = new FileInputStream(file);
body = new byte[is.available()];
is.read(body);
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Disposition", "attchement;filename=" + file.getName());
HttpStatus statusCode = HttpStatus.OK;
ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(body, headers, statusCode);
return entity;
}
将图片链接指定到这个controller即可下载这张图片。