上传.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<body>
<h2>Hello World!</h2>
<a href="user/getjson">getjson</a>
<a href="user/getjson2">getjson2</a>
<form action="toupload" method="post" enctype="multipart/form-data" >
username:<input type="text" name="username"><br>
file:<input type="file" name="myfile"><br>
<input type="submit" value="保存">
</form>
</body>
</html>
下载.jsp
<body>
<a href="down?fname=${filename}">下载</a>
<img src="uploadimage/${filename}">
</body>
web.java
@Controller
public class JsonController {
@RequestMapping("/toupload")
public String upload( MultipartFile myfile,
String username,
HttpServletRequest request){
String path=request.getRealPath("uploadimage");
System.out.println("path="+path);
try {
myfile.transferTo(new File(path+"/"+myfile.getOriginalFilename()));//复制
} catch (IOException e) {
e.printStackTrace();
}
request.setAttribute("filename",myfile.getOriginalFilename());
return "success";
}
@RequestMapping("/down")
public ResponseEntity<byte[]> down(String fname,HttpServletRequest request){
//下载的文件
String path=request.getRealPath("/uploadimage");
File f=new File(path+"/"+fname);
ResponseEntity<byte[]> rsp= null;
try {
//设置响应的头信息
HttpHeaders httpHeaders=new HttpHeaders();
httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);//响应的信息类型
httpHeaders.setContentDispositionFormData("attachment", URLEncoder.encode(fname,"utf-8"));
rsp = new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(f),httpHeaders, HttpStatus.CREATED);
} catch (IOException e) {
e.printStackTrace();
}
return rsp;
}
}