zoukankan      html  css  js  c++  java
  • Spring文件上传Demo

    package com.smbea.controller;
    
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.Iterator;
    
    import javax.servlet.http.HttpServletRequest;
    
    import org.apache.commons.io.FileUtils;
    import org.apache.log4j.Logger;
    import org.springframework.context.annotation.Scope;
    import org.springframework.stereotype.Controller;
    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.bind.annotation.ResponseBody;
    import org.springframework.web.multipart.MultipartFile;
    import org.springframework.web.multipart.MultipartHttpServletRequest;
    import org.springframework.web.multipart.commons.CommonsMultipartFile;
    
    import com.smbea.po.Member;
    import com.smbea.utils.CommonUtils;
    import com.smbea.utils.Constants;
    
    /**
     * 文件上传
     * @author hapday
     * 2015年5月21日  下午12:03:22
     */
    @Controller
    @Scope(value = "prototype")
    @RequestMapping(value = "/demo")
    public class FileUploadController {
    	private static final Logger logger = Logger.getLogger(FileUploadController.class);
    
    	/**
    	 * 多文件上传
    	 * @param name
    	 * @param commonsMultipartFiles
    	 * @param request
    	 * @return
    	 */
    	@RequestMapping(value = "/file/fileUpload1", method = RequestMethod.POST)
    	public @ResponseBody String fileUpload1(@RequestParam("name") String name,
    				@RequestParam("fileToUpload") CommonsMultipartFile [] commonsMultipartFiles, HttpServletRequest request) {
    		long startTime = System.currentTimeMillis();
    		logger.info("FileUploadController-fileUpload1-startTime=" + startTime);
    		
    		if(null == commonsMultipartFiles || 0 == commonsMultipartFiles.length){
    			return Constants.FAILURE;
    		}
    		
    		for(int index = 0, length = commonsMultipartFiles.length; index < length; index++){
    			CommonsMultipartFile commonsMultipartFile = commonsMultipartFiles[index];
    			
    			if(null == commonsMultipartFile || commonsMultipartFile.isEmpty()){
    				continue;
    			}
    			
    			String originalFilename = commonsMultipartFile.getOriginalFilename();
    			String contentType = commonsMultipartFile.getContentType();
    			String fileName = commonsMultipartFile.getName();
    			long fileSize = commonsMultipartFile.getSize();
    			
    			logger.info("name = " + name + ", originalFilename = " + originalFilename
    					+ ", contentType = " + contentType + ", fileName = " + fileName
    					+ ", fileSize = " + fileSize);
    			
    //			String extensionName = originalFilename.substring(originalFilename.indexOf("."));		// 扩展名
    			String newFileName = CommonUtils.UUIDGenerator() + "_" + originalFilename;
    			String destinationPath = request.getSession().getServletContext().getRealPath("/upload/" + newFileName);		// 存放位置
    			logger.info("destinationPath = " + destinationPath);
    			File destFile = new File(destinationPath);
    			
    			try {
    				FileUtils.copyInputStreamToFile(commonsMultipartFile.getInputStream(), destFile);
    			} catch (IOException e) {
    				e.printStackTrace();
    			}
    			
    			Member member = new Member();
    			member.setName(name);
    //			member.setPhotoPath("/upload/" + newFileName);
    		}
    		
    		logger.info("FileUploadController-fileUpload1-耗时=" + (System.currentTimeMillis() - startTime));
    		return Constants.SUCCESS;
    	}
    
    	@RequestMapping(value = "/file/fileUpload2", method = RequestMethod.POST)
    	public @ResponseBody String fileUpload2(@RequestParam("name") String name,
    			HttpServletRequest request) {
    		long startTime = System.currentTimeMillis();
    		logger.info("FileUploadController-fileUpload2-startTime=" + startTime);
    		
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;   
            MultipartFile multipartFile = multipartRequest.getFile("fileToUpload"); 
    //        CommonsMultipartFile commonsMultipartFile = (CommonsMultipartFile) multipartRequest;
    		
    		if(null == multipartFile){
    			return Constants.FAILURE;
    		}
    		
    		String originalFilename = multipartFile.getOriginalFilename();
    		String contentType = multipartFile.getContentType();
    		String fileName = multipartFile.getName();
    		long fileSize = multipartFile.getSize();
    		
    		logger.info("name = " + name + ", originalFilename = " + originalFilename
    				+ ", contentType = " + contentType + ", fileName = " + fileName
    				+ ", fileSize = " + fileSize);
    		
    //			String extensionName = originalFilename.substring(originalFilename.indexOf("."));		// 扩展名
    		String newFileName = CommonUtils.UUIDGenerator() + "_" + originalFilename;
    		String destinationPath = request.getSession().getServletContext().getRealPath("/upload/" + newFileName);		// 存放位置
    		logger.info("destinationPath = " + destinationPath);
    		File destFile = new File(destinationPath);
    		
    		try {
    			FileUtils.copyInputStreamToFile(multipartFile.getInputStream(), destFile);
    		} catch (IOException e) {
    			e.printStackTrace();
    		}
    		
    		Member member = new Member();
    		member.setName(name);
    //		member.setPhotoPath("/upload/" + newFileName);
    		
    		logger.info("FileUploadController-fileUpload2-耗时=" + (System.currentTimeMillis() - startTime));
    		return Constants.SUCCESS;
    	}
    	
    	/**
    	 * 文件上传
    	 * @param name
    	 * @param commonsMultipartFiles
    	 * @param request
    	 * @return
    	 */
    	@RequestMapping(value = "/file/fileUpload3", method = RequestMethod.POST)
    	public @ResponseBody String fileUpload3(@RequestParam("name") String name,
    				@RequestParam("fileToUpload") CommonsMultipartFile commonsMultipartFile, HttpServletRequest request) {
    		long startTime = System.currentTimeMillis();
    		logger.info("FileUploadController-fileUpload1-startTime=" + startTime);
    		
    		if(null == commonsMultipartFile){
    			return Constants.FAILURE;
    		}
    		
    		String originalFileName = commonsMultipartFile.getOriginalFilename();
    		String contentType = commonsMultipartFile.getContentType();
    		String fileName = commonsMultipartFile.getName();
    		long fileSize = commonsMultipartFile.getSize();
    		
    		logger.info("name = " + name + ", originalFilename = " + originalFileName
    				+ ", contentType = " + contentType + ", fileName = " + fileName
    				+ ", fileSize = " + fileSize);
    		
    //			String extensionName = originalFilename.substring(originalFilename.indexOf("."));		// 扩展名
    		String newFileName = CommonUtils.UUIDGenerator() + "_" + originalFileName;
    		String destinationPath = request.getSession().getServletContext().getRealPath("/upload/" + newFileName);		// 存放位置
    		logger.info("destinationPath = " + destinationPath);
    		File destFile = new File(destinationPath);
    		
    		try {
    			FileUtils.copyInputStreamToFile(commonsMultipartFile.getInputStream(), destFile);
    		} catch (IOException e) {
    			e.printStackTrace();
    		}
    		
    		Member member = new Member();
    		member.setName(name);
    //		member.setPhotoPath("/upload/" + newFileName);
    		
    		logger.info("FileUploadController-fileUpload3-耗时=" + (System.currentTimeMillis() - startTime));
    		return Constants.SUCCESS;
    	}
    	
    	@RequestMapping(value = "/file/fileUpload4", method = RequestMethod.POST)
    	public @ResponseBody String fileUpload4(@RequestParam("name") String name, @RequestParam("fileToUpload") CommonsMultipartFile commonsMultipartFile,
    			HttpServletRequest request) {
    		long startTime = System.currentTimeMillis();
    		logger.info("FileUploadController-fileUpload4-startTime=" + startTime);
    		
    		if(null == commonsMultipartFile){
    			return Constants.FAILURE;
    		}
    		
    		String originalFilename = commonsMultipartFile.getOriginalFilename();
    		String contentType = commonsMultipartFile.getContentType();
    		String fileName = commonsMultipartFile.getName();
    		long fileSize = commonsMultipartFile.getSize();
    		
    		logger.info("name = " + name + ", originalFilename = " + originalFilename
    				+ ", contentType = " + contentType + ", fileName = " + fileName
    				+ ", fileSize = " + fileSize);
    		
    //			String extensionName = originalFilename.substring(originalFilename.indexOf("."));		// 扩展名
    		String newFileName = CommonUtils.UUIDGenerator() + "_" + originalFilename;
    		String destinationPath = request.getSession().getServletContext().getRealPath("/upload/" + newFileName);		// 存放位置
    		logger.info("destinationPath = " + destinationPath);
    		File destFile = new File(destinationPath);
    		
    		try {
    			FileUtils.copyInputStreamToFile(commonsMultipartFile.getInputStream(), destFile);
    		} catch (IOException e) {
    			e.printStackTrace();
    		}
    		
    		Member member = new Member();
    		member.setName(name);
    //		member.setPhotoPath("/upload/" + newFileName);
    		
    		logger.info("FileUploadController-fileUpload4-耗时=" + (System.currentTimeMillis() - startTime));
    		return Constants.SUCCESS;
    	}
    	
    	/**
    	 * 多文件上传
    	 * @param name
    	 * @param multipartRequest
    	 * @param request
    	 * @return
    	 */
    	@RequestMapping(value = "/file/fileUpload5", method = RequestMethod.POST)
    	public @ResponseBody String fileUpload5(@RequestParam("name") String name,
    			HttpServletRequest request) {
    		long startTime = System.currentTimeMillis();
    		logger.info("FileUploadController-fileUpload5-startTime=" + startTime);
    		
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;   
    		
    		if(null == multipartRequest || !multipartRequest.getFileNames().hasNext()){
    			return Constants.FAILURE;
    		}
    		
    		for (Iterator<?> fileIterator = multipartRequest.getFileNames(); fileIterator.hasNext();) {  
    	        String key = (String) fileIterator.next();  
    	        MultipartFile multipartFile = multipartRequest.getFile(key);  
    
    	        if(null == multipartFile || 0 == multipartFile.getSize()){
    	        	continue;
    	        }
    	        
    			String originalFilename = multipartFile.getOriginalFilename();
    			String contentType = multipartFile.getContentType();
    			String fileName = multipartFile.getName();
    			long fileSize = multipartFile.getSize();
    
    			logger.info("name = " + name + ", originalFilename = "
    					+ originalFilename + ", contentType = " + contentType
    					+ ", fileName = " + fileName + ", fileSize = " + fileSize);
    
    			String newFileName = CommonUtils.UUIDGenerator() + "_"
    					+ originalFilename;
    
    			String fileUploadPath = multipartRequest.getSession()
    					.getServletContext()
    					.getRealPath(Constants.FILE_UPLOAD_PATH);
    
    			logger.info("fileUploadPath = " + fileUploadPath);
    			
    			try {
    				this.saveFileFromInputStream(multipartFile.getInputStream(),
    						fileUploadPath, newFileName);
    			} catch (Exception e) {
    				e.printStackTrace();
    			}  
    			
    			Member member = new Member();
    			member.setName(name);
    //			member.setPhotoPath(Constants.FILE_UPLOAD_PATH + newFileName);
    	    }  
    
    		logger.info("FileUploadController-fileUpload5-耗时=" + (System.currentTimeMillis() - startTime));
    		return Constants.SUCCESS;
    	}
    
    	@RequestMapping(value = "/file/fileUpload6", method = RequestMethod.POST)
    	public @ResponseBody String fileUpload6(@RequestParam("name") String name, MultipartHttpServletRequest multipartRequest,
    			HttpServletRequest request) {
    		long startTime = System.currentTimeMillis();
    		logger.info("FileUploadController-fileUpload6-startTime=" + startTime);
    		
    //        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;   
    //        MultipartFile multipartFile = multipartRequest.getFile("fileToUpload"); 
    //        CommonsMultipartFile commonsMultipartFile = (CommonsMultipartFile) multipartRequest;
    		
    		if(null == multipartRequest || !multipartRequest.getFileNames().hasNext()){
    			return Constants.FAILURE;
    		}
    		
    		
    		for (Iterator<?> fileIterator = multipartRequest.getFileNames(); fileIterator.hasNext();) {  
    			String key = (String) fileIterator.next();  
    			MultipartFile multipartFile = multipartRequest.getFile(key);  
    			
    			if(null == multipartFile || 0 == multipartFile.getSize()){
    				continue;
    			}
    			
    			String originalFilename = multipartFile.getOriginalFilename();
    			String contentType = multipartFile.getContentType();
    			String fileName = multipartFile.getName();
    			long fileSize = multipartFile.getSize();
    			
    			logger.info("name = " + name + ", originalFilename = "
    					+ originalFilename + ", contentType = " + contentType
    					+ ", fileName = " + fileName + ", fileSize = " + fileSize);
    			
    			String newFileName = CommonUtils.UUIDGenerator() + "_"
    					+ originalFilename;
    			
    			String fileUploadPath = multipartRequest.getSession()
    					.getServletContext()
    					.getRealPath(Constants.FILE_UPLOAD_PATH);
    			
    			logger.info("fileUploadPath = " + fileUploadPath);
    			
    			try {
    				this.saveFileFromInputStream(multipartFile.getInputStream(),
    						fileUploadPath, newFileName);
    			} catch (Exception e) {
    				e.printStackTrace();
    			}  
    			
    			Member member = new Member();
    			member.setName(name);
    //			member.setPhotoPath(Constants.FILE_UPLOAD_PATH + newFileName);
    		}  
    		
    		logger.info("FileUploadController-fileUpload6-耗时=" + (System.currentTimeMillis() - startTime));
    		return Constants.SUCCESS;
    	}
    	
    	/**
    	 * 保存文件到制定目录
    	 * @param inputStream
    	 * @param fileUploadPath
    	 * @param newFileName
    	 * @throws IOException
    	 */
    	private void saveFileFromInputStream(InputStream inputStream, String fileUploadPath,
    			String newFileName) throws IOException {
    		File file = new File(fileUploadPath, newFileName);
    		
    		if(!file.exists()){
    			file.createNewFile();
    		}
    		
    		FileOutputStream fileOutputStream = new FileOutputStream(file);
    		byte[] buffer = new byte[1024 * 1024];
    		int bytesum = 0;
    		int byteread = 0;
    		while ((byteread = inputStream.read(buffer)) != -1) {
    			bytesum += byteread;
    			fileOutputStream.write(buffer, 0, byteread);
    			fileOutputStream.flush();
    		}
    		fileOutputStream.close();
    		inputStream.close();
    		
    		logger.info("*** bytesum = " + bytesum);
    	}
    }
    

      

  • 相关阅读:
    PAT(乙级)1007
    PAT(乙级)1006
    PAT(乙级)1005
    PAT(乙级)1004
    C算法实现:将字符串中的数字返回为整型数
    PAT(乙级)1002
    PAT(乙级)1001
    NOI接水问题
    【BZOJ】【2756】【SCOI2012】奇怪的游戏
    【BZOJ】【2631】Tree
  • 原文地址:https://www.cnblogs.com/hapday/p/6337013.html
Copyright © 2011-2022 走看看