单个文件的上传
SpringMVC中提供了专门的类CommonsMultipartResvoler支持下载
一、在SpringMVC中配置文件
<bean class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="10485760"></property>//最大上传kb
<property name="defaultEncoding" value="utf-8"></property>//默认编码
</bean>
==引入的jar包==
1.commons-fileupload.jar
2.commons-io-1.4.jar
代码:
@RequestMapping("/oneUpload")
public String oneUpload(@RequestParam("imageFile") MultipartFile imageFile, HttpServletRequest request){
String uploadUrl = request.getSession().getServletContext().getRealPath("/")+"upload/";
System.out.println("uploadUrl:"+uploadUrl);
String filename = imageFile.getOriginalFilename();
File dir = new File(uploadUrl);
if (!dir.exists()){
dir.mkdirs();
}
System.out.println();
File targetFile = new File(uploadUrl+filename);
if (!targetFile.exists()){
try {
targetFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
imageFile.transferTo(targetFile);
} catch (IOException e) {
e.printStackTrace();
}
return "success";
}
JSP页面代码
<form action="${pageContext.request.contextPath}/oneUpload" method="post" enctype="multipart/form-data">
<input type="file" name="imageFile">
<input type="submit" name="上传">
</form>
文件的下载
设置编码格式为text/html;charset=utf-8;
设置header中Content-dispositon属性值为attachment;filename = 文件名
设置header中Content-length属性,值为文件的大小
代码
@RequestMapping("/download.do")
public String download(@RequestParam String filename, HttpServletRequest request, HttpServletResponse response){
response.setContentType("text/html;charset = uft-8");
try {
request.setCharacterEncoding("utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
BufferedInputStream bis =null;
BufferedOutputStream bos =null;
String ctxPath = request.getSession().getServletContext().getRealPath("/")+"upload/";
String downloadPath = ctxPath+filename;
System.out.println(downloadPath);
try {
long filelength = new java.io.File(downloadPath).length();
response.setContentType("application/x-msdownload");
response.setHeader("Content-Length", String.valueOf(filelength));
response.setHeader("Content-disposition","attachment;filename="+new String(filename.getBytes("UTF-8"),"iso-8859-1"));
bis = new BufferedInputStream(new FileInputStream(downloadPath));
bos = new BufferedOutputStream(response.getOutputStream());
byte[] buff = new byte[2048];
int byteRead ;
while ((byteRead = bis.read(buff,0,buff.length))!=-1){
bos.write(buff,0,byteRead);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if (bis!=null){
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (bos!=null){
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return "success";
}
JSP中的标签
<a href="${pageContext.request.contextPath}/download.do?filename=DSC_0001.jpg">DSC_0001.jpg</a>