SpringMVC结合ajaxfileupload文件无刷新上传

longshengguoji 2015-12-08

  jQuery没有提供ajax的文件上传,我们可以通过ajaxfileupload实现ajax文件的上传。其实ajaxfileupload文件上传特别的简单。下面就演示一下在SpringMVC中实现ajax的文件上传。

      1、后台接收代码

     首先在spring的配置文件中添加文件上传配置

     

<!-- 文件上传 -->
	<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<property name="defaultEncoding" value="UTF-8"/>  
	</bean>

    再写文件接收的代码

       

package org.andy.controller;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;

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

import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;
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.multipart.commons.CommonsMultipartFile;


@Controller
@RequestMapping("/upload")
public class UploadController {

	private static final Logger LOG = Logger.getLogger(UploadController.class);

	private static final HashMap<String, String> TypeMap = new HashMap<String, String>();

	static {
		TypeMap.put("image", "gif,jpg,jpeg,png,bmp");
		TypeMap.put("flash", "swf,flv");
		TypeMap.put("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");
		TypeMap.put("file", "doc,docx,xls,xlsx,ppt,pptx,htm,html,txt,dwg,pdf");
	}

	/**
	 * 文件上传 之 图片上传
	 * 
	 * @param file
	 * @param request
	 * @return message: -1 没有文件上传 0 上传成功 1 上传失败 2 文件超过上传大小 3 文件格式错误 4 上传文件路径非法 5 上传目录没有写权限
	 *       
	 * 
	 */
	@RequestMapping(value = "/imageUpload", method = RequestMethod.POST)
	public void imageUpload(
			@RequestParam("file") CommonsMultipartFile file,
			@RequestParam(required = false) String filePre, HttpServletRequest request, HttpServletResponse response) {
		LOG.info("file name is :" + file.getOriginalFilename());
		
		if (!file.isEmpty()) {
			ServletContext servletContext = request.getSession()
					.getServletContext();
			String uploadPath = servletContext.getRealPath("/")
					+ "uploadImage/";
			// 文件上传大小
			long fileSize = 3 * 1024 * 1024;

			if (file.getSize() > fileSize) {
				backInfo(response, false, 2, "");
				return;
			}

			String OriginalFilename = file.getOriginalFilename();

			String fileSuffix = OriginalFilename.substring(
					OriginalFilename.lastIndexOf(".") + 1).toLowerCase();
			if (!Arrays.asList(TypeMap.get("image").split(",")).contains(
					fileSuffix)) {
				backInfo(response, false, 3, "");
				return;
			}

			if (!ServletFileUpload.isMultipartContent(request)) {
				backInfo(response, false, -1, "");
				return;
			}

			// 检查上传文件的目录
			File uploadDir = new File(uploadPath);
			if (!uploadDir.isDirectory()) {
				if (!uploadDir.mkdir()) {
					backInfo(response, false, 4, "");
					return;
				}
			}

			// 是否有上传的权限
			if (!uploadDir.canWrite()) {
				backInfo(response, false, 5, "");
				return;
			}
			
			//新文件名
			String newname = "";
			if(null != filePre){
				newname += filePre;//对应模块上传的文件名前缀
			}
			
			 newname +=	DateFormater.format(new Date(),
					DateFormater.DATETIME_PATTERN) + "." + fileSuffix;

			File saveFile = new File(uploadPath, newname);

			try {
				file.transferTo(saveFile);
				backInfo(response, true, 0, newname);
			} catch (Exception e) {
				LOG.error(e.getMessage(), e);
				backInfo(response, false, 1, "");
				return;
			}
		} else {
			backInfo(response, false, -1, "");
			return;
		}

	}

	// 返回信息
	private void backInfo(HttpServletResponse response, boolean flag, int message,
			String fileName) {
		String json  = "";
		if (flag) {
			json = "{ \"status\": \"success"; 
		} else {
			json = "{ \"status\": \"error"; 
		}
		json += "\",\"fileName\": \"" + fileName + "\",\"message\": \"" + message + "\"}";
		try {
			response.setContentType("text/html;charset=utf-8");
			response.getWriter().write(json);
		} catch (IOException e) {
			LOG.error(e.getMessage(), e);
		}
	}

}

         2、前台接受代码

          使用ajaxfileupload时,首先下载ajaxfileupload文件,导入对应的js文件

    

<script type="text/javascript" src="js/ajaxfileupload.js"></script>

       文件传输字段必须为file类型,如下:

<input type="file" id="file" name="file" onchange="ajaxFileUpload();"/>


      其次,处理上传文件:

           

//ajax 实现文件上传 
		function ajaxFileUpload() {
			
			$.ajaxFileUpload({
				url : "upload/imageUpload.shtml",
				secureuri : false,
				data : {
					filePre : "feedback",
					p : new Date()
				},
				fileElementId : "file",
				dataType : "json",
				success : function(data) {
					if (data.status == "success") {
						//上传成功
					}
					switch(data.message){
					 //解析上传状态
						case "0" : //上传成功
						           break;
						case "-1" : //上传文件不能为空
						          break;
						default: //上传失败
						     break;
					}
				},
				error : function(data) {
					//上传失败
				}
			});

		}

http://blog.csdn.net/fengshizty

原文链接http://blog.csdn.net/fengshizty/article/details/43083309

其实很简单。

相关推荐