springmvc上传2

package com.dongly.upload;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;

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

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
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.CommonsMultipartResolver;

@Controller
public class UploadFile {

	/**
	 * 如果只是上传一个文件,则只需要MultipartFile类型接收文件即可,而且无需显式指定@RequestParam注解
	 * 如果想上传多个文件,那么这里就要用MultipartFile[]类型来接收文件,并且还要指定@RequestParam注解
	 * 并且上传多个文件时,前台表单中的所有<input type="file"/>的name都应该是myfiles,
	 * 否则参数里的myfiles无法获取到所有上传文件
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/many")
	public String singleUploadFile(HttpServletRequest request, HttpServletResponse response) {
		// 创建一个通用的多部分解析器
		CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(request.getServletContext());
		// 判断 request 是否有文件上传,即多部分请求
		if (commonsMultipartResolver.isMultipart(request)) {
			// 转换成多部分request
			MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) (request);
			// 取得request中的所有文件名
			Iterator<String> fileNames = multipartHttpServletRequest.getFileNames();
			while (fileNames.hasNext()) {
				String next = fileNames.next();
				// 取得上传文件
				MultipartFile file = multipartHttpServletRequest.getFile(next);
				// 判断文件是否为空,为空说明文件不存在
				if (!file.isEmpty()) {
					// 取得当前上传文件的文件名称
					String fileName = file.getOriginalFilename();
					
					String realPath = request.getServletContext().getRealPath("img");
					File path = new File(realPath,fileName);
					if (!path.exists()) {
						path.mkdirs();
					}
					try {
						file.transferTo(path);
						request.setAttribute("fileUrl", "img/" + fileName);
					} catch (IllegalStateException | IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
		return "batchUploadFile";
	}
	
	@RequestMapping("/two")
	public String two(@RequestParam("file1") MultipartFile[] file1,HttpServletRequest request, HttpServletResponse response) {
		
		for (MultipartFile multipartFile : file1) {
			if(!multipartFile.isEmpty()){
				// 取得当前上传文件的文件名称
				String fileName = multipartFile.getOriginalFilename();
				
				String realPath = request.getServletContext().getRealPath("img");
				File path = new File(realPath,fileName);
				if (!path.exists()) {
					path.mkdirs();
				}
				try {
					multipartFile.transferTo(path);
					request.setAttribute("fileUrl", "img/" + fileName);
				} catch (IllegalStateException | IOException e) {
					e.printStackTrace();
				}
			}
		}
				
		return "batchUploadFile";
	}
}

猜你喜欢

转载自xhnszdm.iteye.com/blog/2305887
今日推荐