SpringMVC项目前台利用ajaxFileUpload传递图片后台接收

今天上午一直在看这个问题,就是图片上传到后台之后发现图片无法正确的显示了,很是诧异。

诧异之余,不得不去想为什么会出现这样的情况,那么要看我后台接收参数的方式,在看后台之前,我们先来看看前台是如何上传图片的。

对于的页面代码:

<div> 
<input id="myfile" name="myfile" type="file" style="width:300px;"/>
<button id="btn" type="submit">插入图片</button>
</div>

我们在button上面绑定一个事件,当点击按钮的时候执行下面的代码:

  $.ajaxFileUpload({  
                	        url : "http://localhost:8080/Shopping/filecontroller/uploadservlet",  
                	        secureuri : false,// 一般设置为false  
                	        fileElementId : "myfile",// 文件上传表单的id <input type="file" id="fileUpload" name="file" />  
                	        dataType : 'json',// 返回值类型 一般设置为json  
                	        method:"post",
                	        data: {'type': 1},
                	        success : function(data) // 服务器成功响应处理函数  
                	        {  
                	        	console.log(data);
                	        },  
                	        error : function(data)// 服务器响应失败处理函数  
                	        {  
                	            console.log(data);  
                	        }  
                	    }); 
                	

这个是我们前台的代码,我们后台应该如何实现将图片保存到对应的文件夹

	@RequestMapping(value = "/uploadservlet", method = RequestMethod.POST, produces = "text/html;charset=utf-8")
	protected void uploadServlet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		log.info("-------------------开始调用上传文件uploadservlet接口-------------------");
		try {
			if (request instanceof MultipartHttpServletRequest) {
				MultipartHttpServletRequest mr = (MultipartHttpServletRequest) request;
				List<MultipartFile> multipartFile = mr.getFiles("myfile");
				Map<String, Object> map = new HashMap<String, Object>();
				String result = "0000";
				String msg = "添加成功";
				if (null != multipartFile && !multipartFile.isEmpty()) {
					MultipartFile file = multipartFile.get(0);
					String name=file.getOriginalFilename();
					String path = this.getClass().getClassLoader().getResource("/").getPath();
					int index = path.indexOf("Shopping");
					path = path.substring(0, index + "Shopping".length()) + "/WebContent/resources/upload/";
					path = path + File.separator + name;
					File uploadFile = new File(path);
					FileCopyUtils.copy(file.getInputStream(), new FileOutputStream(uploadFile));
				}
			}

		} catch (Exception e) {

		}
		log.info("-------------------结束调用上传文件uploadservlet接口-------------------");
	}

上面是我们在SpringMVC中应该调用的函数的代码,其实应该主要的一点是,这个前后台有一个对应关系:

				List<MultipartFile> multipartFile = mr.getFiles("myfile");

这个里面有个getFiles("myfile"),这个应该和前台的页面的input里面的标签有个id和name相对应

猜你喜欢

转载自blog.csdn.net/datouniao1/article/details/79668043
今日推荐