ajaxFileUpload+springmvc文件上傳例子


  //文件上傳頁面


          <div > <input type="file" id="file" name="file" onchange="ajaxFileUpload();"/> <input type="hidden" id="pic" name="pic" /> </div>
//ajax 實現文件上傳 

function ajaxFileUpload() {
var picpath="";
	$.ajaxFileUpload({
	    url : "../upload/imageUpload",
	       fileElementId:'file',
	       dataType : "json", 
	       success: function(data){
	        $("#picshow").append("<img src='http://www.iherebuy.com:8089/img/tempImg/"+data.fileName+"' width='80px' height='80px'/>")
	       alert('success');
	        picpath=$("#pic").val()+data.fileName+",";
	        $("#pic").val(picpath);
	       },
	       error: function(data)
	       {
	          alert("上傳失敗");
	        }
           }
);
	}

  


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

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.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import ease.shopping.util.UUIDGenerator;

/**
 * 文件上傳類
 * @author Administrator
 *
 */
@RestController
@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");
	}
	
	// 設置文件上傳大小
	public static long fileSize = 3 * 1024 * 1024;
	/**
	 * 文件上傳
	 * 
	 * @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()) {
		
			//當文件超過設置的大小時,則不運行上傳
			if (file.getSize() > fileSize) {
				backInfo(response, false, 2, "");
				return;
			}
			//獲取文件名后綴
			String OriginalFilename = file.getOriginalFilename();
			String fileSuffix = OriginalFilename.substring(
					OriginalFilename.lastIndexOf(".") + 1).toLowerCase();
			
			//String fileSuffix="jpeg";
			
			//判斷該類型的文件是否在允許上傳的文件類型內
			if (!Arrays.asList(TypeMap.get("file").split(",")).contains(
					fileSuffix)) {
				backInfo(response, false, 3, "");
				return;
			}
			if (!ServletFileUpload.isMultipartContent(request)) {
				backInfo(response, false, -1, "");
				return;
			}
			// 檢查上傳文件的目錄
			File uploadDir = new File(SysProperty.BASE_PATH);
			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 +=	UUIDGenerator.getUUIDrand() + "." + fileSuffix;

			try {

				 //創建文件
				File saveFile = new File(SysProperty.BASE_PATH, newname);
				//保存文件
				file.transferTo(saveFile);
				//FileTranser.saveFielByFileName(file, uploadPath, newname);
				backInfo(response, true, 0, newname);
			} catch (Exception e) {
				LOG.error(e.getMessage(), e);
				backInfo(response, false, 1, "");
				return;
			}
		} else {
			backInfo(response, false, -1, "");
			return;
		}

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

}

  需要用到的js文件鏈接:http://pan.baidu.com/s/1kTMZDQ3 密碼:rkoq


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM