JQuery与springmvc实现单个文件上传操作

1. 导入JQuery相关JS文件

<script src="<@full_path path="js/jquery.js"/>" type="text/javascript"></script>

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


2. 页面调用以及JS代码:

			<th>图片上传:</th>
			<td>
				<A hideFocus class="addfileA" id="aComposeAttach" href="#" >
					<INPUT hideFocus class=addfileI type=file size=1 name="file" id="defaultIconUpload" οnchange="return ajaxUpload('defaultIconUpload','defaultIconImg','defaultIcon');">
				</A>
				<img width="150" height="150"  src="<@full_path path="img/no_picture.gif"/>" id="defaultIconImg" />
				<input type="hidden" maxlength="20" class="" id="defaultIcon" name="defaultIcon" />
			</td>

//上传方法
function ajaxUpload(id,imgId,hiddId){  
   var content= document.getElementById(id).value; 
   if(content.length==''){
	   alert("请选择图片!");
	   return false;
   }
   //webapp/
   var baseUrl = "<@full_path path="/"/>";
   //alert("baseUrl is " + baseUrl + ",id is " + id);
   $.ajaxFileUpload
   (  
        { 
			url: baseUrl + 'upload/app', //你处理上传文件的服务端
			secureuri:false,
			fileElementId:id,
			dataType: 'json',
			success: function (data, status)
			{				
				$("#"+imgId).attr("src",baseUrl+"uploads/"+data.file_path);
				$("#"+hiddId).val("uploads/"+data.file_path);
				//alert("上传成功!");
				
			},
			error: function (data, status, e)
			{  
			   alert("上传图片失败!");
			}
		}
    );
    return false;
}

3. 后台操作JAVA代码:

@RequestMapping("/upload")
@Controller
public class FileUploadController {
	
	private final static Logger logger=LoggerFactory.getLogger(FileUploadController.class);
	
	public static class FileUploadResp{
		
		/**
		 * 结果:0 表示成功;1 表示失败
		 */
		private int result;
		
		/**
		 * 结果说明
		 */
		private String desc;
		
		/**
		 * 上传文件保存路径
		 */
		@JsonProperty("file_path")
		private String filePath;
		
		public FileUploadResp(){}
		
		public FileUploadResp(int result, String desc) {
			super();
			this.result = result;
			this.desc = desc;
		}
		
		
		
		public FileUploadResp(String filePath) {
			super();
			this.result = 0;
			this.desc = "上传成功";
			this.filePath = filePath;
		}

		public int getResult() {
			return result;
		}
		public void setResult(int result) {
			this.result = result;
		}
		public String getDesc() {
			return desc;
		}
		public void setDesc(String desc) {
			this.desc = desc;
		}

		@JsonIgnore
		public String getFilePath() {
			return filePath;
		}

		public void setFilePath(String filePath) {
			this.filePath = filePath;
		}
		
		public String toString(){
			return ToStringBuilder.reflectionToString(this);
		}
		
	}
	
	@RequestMapping(value="/{module}/{resType}",method = RequestMethod.POST)
	public @ResponseBody Object uploadToTmp(HttpServletRequest request,@PathVariable String module,@PathVariable String resType,@RequestParam("file") MultipartFile file) throws IllegalStateException, IOException {
		String relPathOfSavedDir=module+"/"+resType+"/";
		try {
			File savedDir = prepareSavedDir(request, relPathOfSavedDir);
			String savedFileName=getSavedFileName(file.getOriginalFilename());
			file.transferTo(new File(savedDir,savedFileName));
			return new FileUploadResp(relPathOfSavedDir+savedFileName);
		} catch (Exception e) {
			logger.error(e.getLocalizedMessage(), e);
			return new FileUploadResp(1,e.getLocalizedMessage());
		}
	}

	@RequestMapping(value="/menu/{resType}/{baseLine}/{org}/{section}",method = RequestMethod.POST)
	public @ResponseBody Object uploadForMenu(HttpServletRequest request,@PathVariable String resType,@PathVariable String baseLine,@PathVariable String org,@PathVariable String section,@RequestParam("file") MultipartFile file) throws IllegalStateException, IOException {
		String relPathOfSavedDir="menu/"+resType+"/"+baseLine+"/"+org+"/"+section+"/";
		try {
			File savedDir = prepareSavedDir(request, relPathOfSavedDir);
			String savedFileName=getSavedFileName(file.getOriginalFilename());
			file.transferTo(new File(savedDir,savedFileName));
			return new FileUploadResp(relPathOfSavedDir+savedFileName);
		} catch (Exception e) {
			logger.error(e.getLocalizedMessage(), e);
			return new FileUploadResp(1,e.getLocalizedMessage());
		}
	}
	
	@RequestMapping(value="/app",method = RequestMethod.POST)
	public @ResponseBody Object uploadForApp(HttpServletRequest request,@RequestParam("file") MultipartFile file) throws IllegalStateException, IOException {
		String relPathOfSavedDir="app/";
		try {
			File savedDir = prepareSavedDir(request, relPathOfSavedDir);
			String savedFileName=getSavedFileName(file.getOriginalFilename());
			file.transferTo(new File(savedDir,savedFileName));
			return new FileUploadResp(relPathOfSavedDir+savedFileName);
		} catch (Exception e) {
			logger.error(e.getLocalizedMessage(), e);
			return new FileUploadResp(1,e.getLocalizedMessage());
		}
	}
	
	private File prepareSavedDir(HttpServletRequest request,String relativePath) throws Exception{
		File dir=new File(request.getSession().getServletContext().getRealPath("/uploads/"+relativePath));
		if(!dir.exists()){
			if(!dir.mkdirs()){
				throw new Exception("创建保存目录失败");
			}
		}
		return dir;
	}
	
	private String getSavedFileName(String origFileName){
		return DateHelper.getCurrentTimeStamp("yyyyMMddHHmmss") +"-"+RandomStringUtils.randomNumeric(5)+"."+FilenameUtils.getExtension(origFileName);
	}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值