上传文件
上传文件时,存放上传文件的文件夹不能为空,因为编译时,空的文件夹在target目录下是不存在的
导入架包
<!--sahng-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
配置Spring.xml
<!--文件上传 id的名字不能随便起-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="utf-8"></property>
<property name="maxUploadSize" value="10485760"></property>
<!--maxUploadSize , 字节为单位传输-->
</bean>
<!--设置静态资源的访问-->
<mvc:annotation-driven></mvc:annotation-driven>
<mvc:resources mapping="/uploadimage/**" location="/uploadimage/"></mvc:resources>
上传文件测试
upload.jsp
<form action="toupimage" method="post" enctype="multipart/form-data">
username:<input type="text" name="username"><br>
file<input type="file" name="fileimage">
<input type="submit" value="保存">
</form>
test.java
@Controller
public class JsonTest {
@RequestMapping("/toupimage")
public String uploadimage(MultipartFile 名字需要和传过来的参数一致, String username, HttpServletRequest request){
//Multipart 多
System.out.println("username"+username);
String path=request.getRealPath("/uploadimage");//要保存的文件夹路径
System.out.println(path);
try{
fileimage.transferTo(new File(path+"/"+fileimage.getOriginalFilename()));
}catch (IOException e) {
e.printStackTrace();
}
request.setAttribute("filename",fileimage.getOriginalFilename());
return "success";
}
}
下载文件测试
test.jsp
<a href="down?filename=${filename}">下载</a>
test.java
@RequestMapping("/down")
public ResponseEntity<byte[]> downimage(String filename,HttpServletRequest request){
//下载文件的路径
String path=request.getRealPath("/uploadimage");
File file=new File(path+"/"+filename);
ResponseEntity<byte []> rsp=null;
//设置头信息
//创建对象
HttpHeaders httpHeaders=new HttpHeaders();
//设置响应的类型
httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
//Disposition 性格
try {
httpHeaders.setContentDispositionFormData("attachment", URLEncoder.encode(filename,"utf-8"));
rsp = new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),httpHeaders, HttpStatus.CREATED);
} catch (IOException e) {
e.printStackTrace();
}
return rsp;
}