spring 上傳下載

/*
 * package com.jygps.common.web; import java.io.File; import
 * java.io.FileInputStream; import java.io.FileNotFoundException; import
 * java.io.IOException; import java.io.InputStream; import java.io.OutputStream;
 * import java.text.SimpleDateFormat; import java.util.Date; import
 * java.util.Iterator; import javax.servlet.http.HttpServletRequest; import
 * javax.servlet.http.HttpServletResponse; import org.slf4j.Logger; import
 * org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller;
 * import org.springframework.web.bind.annotation.RequestMapping; import
 * org.springframework.web.multipart.MultipartFile; import
 * org.springframework.web.multipart.MultipartHttpServletRequest; import
 * org.springframework.web.multipart.commons.CommonsMultipartResolver; import
 * com.jygps.common.util.Result; import com.jygps.common.util.StringUtil;
 * @Controller
 * @RequestMapping("/fileUploadController") public class FileUploadController
 * extends BaseMultiActionController { Logger logger =
 * LoggerFactory.getLogger(FileUploadController.class);
 * @RequestMapping("/upload.do") public Result<?> upload(HttpServletRequest
 * request, HttpServletResponse response) throws IOException {
 * CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
 * request.getSession().getServletContext()); String imgAddress = ""; if
 * (multipartResolver.isMultipart(request)){ MultipartHttpServletRequest
 * multiRequest = (MultipartHttpServletRequest) request; Iterator<String> iter =
 * multiRequest.getFileNames(); while (iter.hasNext()){ MultipartFile file =
 * multiRequest.getFile((String) iter.next()); if (file != null){ String
 * fileName = file.getOriginalFilename(); String path1 =
 * Thread.currentThread().getContextClassLoader().getResource("").getPath() +
 * File.separator; // 下面的加的日期是爲了防止上傳的名字同樣 fileName = new
 * SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + fileName; String path
 * = path1 + fileName; File localFile = new File(path);
 * if(StringUtil.isBlank(imgAddress)){ imgAddress += fileName; }else{ imgAddress
 * = imgAddress + "," + fileName; } file.transferTo(localFile); } }
 * request.getSession().setAttribute("imgAddress", imgAddress); } return
 * Result.success(imgAddress); }
 * @RequestMapping("/toUpload.do") public String toUpload() { return "upload"; }
 * @RequestMapping("/download") public String download(String fileName,
 * HttpServletRequest request, HttpServletResponse response) {
 * response.setCharacterEncoding("utf-8");
 * response.setContentType("multipart/form-data");
 * response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
 * try{ String path =
 * Thread.currentThread().getContextClassLoader().getResource("").getPath();//
 * 這個download目錄爲啥創建在classes下的 path = path.substring(1); InputStream inputStream
 * = new FileInputStream(new File(path + File.separator + fileName));
 * OutputStream os = response.getOutputStream(); byte[] b = new byte[2048]; int
 * length; while ((length = inputStream.read(b)) > 0){ os.write(b, 0, length); }
 * // 關閉。 os.close(); inputStream.close(); } catch (FileNotFoundException e){
 * e.printStackTrace(); } catch (IOException e){ e.printStackTrace(); } //
 * 返回值要注意,要否則就出現下面這句錯誤! // java+getOutputStream() has already been called for
 * this response return null; } }
 */

package com.jygps.common.web;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.BindException;
import java.util.ArrayList;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

/**
 * *********************************
 * @ClassName: FileUploadController.java
 * @Description: 文件上傳/
 * @author: zenghang
 * @createdAt: 2016年4月6日下午2:12:23
 **********************************
 */
@Controller
public class FileUploadController {
	
	@RequestMapping(value = "/upload", method = RequestMethod.POST)
	public ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, BindException errors)
			throws Exception {
		
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest.getFile("file");
		
		String name = multipartRequest.getParameter("name");
		System.out.println("name: " + name);
		// 得到文件名:
		String realFileName = file.getOriginalFilename();
		System.out.println("得到文件名:" + realFileName);
		// 獲取路徑
		String ctxPath = request.getSession().getServletContext().getRealPath("/") + "images/";
		// 建立文件
		File dirPath = new File(ctxPath);
		if (!dirPath.exists()){
			dirPath.mkdir();
		}
		File uploadFile = new File(ctxPath + realFileName);
		FileCopyUtils.copy(file.getBytes(), uploadFile);
		request.setAttribute("files", loadFiles(request));
		return new ModelAndView("success");
	}
	
	
	@RequestMapping(value = "/upload2", method = RequestMethod.POST)
	public ModelAndView onSubmit2(HttpServletRequest request, HttpServletResponse response, BindException errors)
			throws Exception {
		
		// 轉型爲MultipartHttpRequest
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		// 根據前臺的name名稱獲得上傳的文件
		MultipartFile file = multipartRequest.getFile("file");
		// 得到文件名:
		String realFileName = file.getOriginalFilename();
		// 獲取路徑
		String ctxPath = request.getSession().getServletContext().getRealPath("/") + "\\" + "images\\";
		// 建立文件
		File dirPath = new File(ctxPath);
		if (!dirPath.exists()){
			dirPath.mkdir();
		}
		File uploadFile = new File(ctxPath + realFileName);
		FileCopyUtils.copy(file.getBytes(), uploadFile);
		request.setAttribute("files", loadFiles(request));
		return new ModelAndView("success");
	}
	
	
	@RequestMapping(value = "/upload3", method = RequestMethod.POST)
	public String upload(@RequestParam("file") MultipartFile image, HttpServletRequest request) throws IOException {
		
		String ctxPath = request.getSession().getServletContext().getRealPath("/") + "\\" + "images\\";
		System.out.println("路徑:" + ctxPath);
		File file = new File(ctxPath + "/" + image.getOriginalFilename());
		// FileCopyUtils.copy(image.getBytes(),new
		// File(ctxPath+"/"+image.getOriginalFilename()));
		try{
			image.transferTo(file); // 保存上傳的文件
		}
		catch (IllegalStateException e){
			e.printStackTrace();
		}
		catch (IOException e){
			e.printStackTrace();
		}
		request.setAttribute("files", loadFiles(request));
		return "success";
	}
	
	
	// 多文件上傳
	@RequestMapping(value = "/upload4", method = RequestMethod.POST)
	public List<String> fileUpload(HttpServletRequest request, HttpServletResponse response, BindException errors)
			throws Exception {
		
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		String ctxPath = request.getSession().getServletContext().getRealPath("/") + "\\" + "images\\";
		
		File file = new File(ctxPath);
		if (!file.exists()){
			file.mkdir();
		}
		String fileName = null;
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()){
			// 上傳文件名
			// System.out.println("key: " + entity.getKey());
			MultipartFile mf = entity.getValue();
			fileName = mf.getOriginalFilename();
			File uploadFile = new File(ctxPath + fileName);
			FileCopyUtils.copy(mf.getBytes(), uploadFile);
		}
		List<String> files = loadFiles(request);
		request.setAttribute("files", files);
		return files;
	}
	
	
	// @ModelAttribute("files")//此屬性用於初始類時調用,但上傳文件後不能時時反應上傳文件個數,不適合動態數據
	public List<String> loadFiles(HttpServletRequest request) {
		List<String> files = new ArrayList<String>();
		String ctxPath = request.getSession().getServletContext().getRealPath("/") + "\\" + "images\\";
		File file = new File(ctxPath);
		if (file.exists()){
			File[] fs = file.listFiles();
			String fname = null;
			for (File f : fs){
				fname = f.getName();
				if (f.isFile()){
					files.add(fname);
				}
			}
		}
		return files;
	}
	
	
	@RequestMapping("/download/{fileName}")
	public ModelAndView download(@PathVariable("fileName") String fileName, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		
		response.setContentType("text/html;charset=utf-8");
		request.setCharacterEncoding("UTF-8");
		java.io.BufferedInputStream bis = null;
		java.io.BufferedOutputStream bos = null;
		
		String ctxPath = request.getSession().getServletContext().getRealPath("/") + "\\" + "images\\";
		String downLoadPath = ctxPath + fileName;
		System.out.println(downLoadPath);
		try{
			long fileLength = new File(downLoadPath).length();
			response.setContentType("application/x-msdownload;");
			response.setHeader("Content-disposition", "attachment; filename="
					+ new String(fileName.getBytes("utf-8"), "ISO8859-1"));
			response.setHeader("Content-Length", String.valueOf(fileLength));
			bis = new BufferedInputStream(new FileInputStream(downLoadPath));
			bos = new BufferedOutputStream(response.getOutputStream());
			byte[] buff = new byte[2048];
			int bytesRead;
			while (-1 != (bytesRead = bis.read(buff, 0, buff.length))){
				bos.write(buff, 0, bytesRead);
			}
		}
		catch (Exception e){
			e.printStackTrace();
		}
		finally{
			if (bis != null)
				bis.close();
			if (bos != null)
				bos.close();
		}
		return null;
	}
}



<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<%@ include file="/resource/common/baseTagLibs.jsp"%>
<script type="text/javascript" src="${ctx }/resource/js/tools/jquery-1.9.1.min.js" type="text/javascript"></script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
	i = 1;
	j = 1;
	$(document).ready(function(){
		
		$("#btn_add1").click(function(){
			document.getElementById("newUpload1").innerHTML+='<div id="div_'+i+'"><input  name="file" type="file"  /><input type="button" value="刪除"  onclick="del_1('+i+')"/></div>';
			  i = i + 1;
		});
		
		$("#btn_add2").click(function(){
			document.getElementById("newUpload2").innerHTML+='<div id="div_'+j+'"><input  name="file_'+j+'" type="file"  /><input type="button" value="刪除"  onclick="del_2('+j+')"/></div>';
			  j = j + 1;
		});
	});

	function del_1(o){
	 document.getElementById("newUpload1").removeChild(document.getElementById("div_"+o));
	}
	
	function del_2(o){
		 document.getElementById("newUpload2").removeChild(document.getElementById("div_"+o));
	}

</script>
</head>
<body>

	 <h1>springMVC字節流輸入上傳文件</h1> 
    <form name="userForm1" action="/springMVC7/file/upload" enctype="multipart/form-data" method="post">
		<div id="newUpload1">
			<input type="file" name="file">
		</div>
		
		<input type="button" id="btn_add1" value="增長一行" >
		<input type="submit" value="上傳" >
 	</form> 
 	<br>
 	<br>
 	<hr align="left" width="60%" color="#FF0000" size="3">
 	<br>
 	<br>
 	 <h1>springMVC包裝類上傳文件</h1> 
 	<form name="userForm2" action="/springMVC7/file/upload2" enctype="multipart/form-data" method="post"">
 		<div id="newUpload2">
			<input type="file" name="file">
		</div>
		<input type="button" id="btn_add2" value="增長一行" >
		<input type="submit" value="上傳" >
		
		
 	</form> 
</body>
</html>
相關文章
相關標籤/搜索