SpringMVC框架,MultipartFile上传文件始终是NULL

由于使用的是无配置文件的SSM框架,所以配置文件上传有点费劲 

以下是无xml的配置文件上传

@Configuration
@EnableWebMvc
@ComponentScan("com.study.controller")
public class WebConfig extends WebMvcConfigurerAdapter {
	
	@Bean 
	public ViewResolver viewResolver(){
		InternalResourceViewResolver resolver = new InternalResourceViewResolver();
		resolver.setPrefix("/jsp/");
		resolver.setSuffix(".jsp");
		resolver.setExposeContextBeansAsAttributes(true);
		resolver.setViewClass(JstlView.class);
		return resolver;
	}
	
	/*
     * resolve the multipart file upload.
        此处一定要在bean指明multipartResolver
        否则就是配置了也是null指针异常
        我此处挣扎来了一个小时
     */
    @Bean("multipartResolver")
    public MultipartResolver getResolver(){
                //更改为multipartResolver即可。
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
        multipartResolver.setDefaultEncoding("utf-8");
        multipartResolver.setMaxUploadSize(10485760000l);
        System.out.println("init resolver...");
        return multipartResolver;
    }
	
	//配置静态资源的处理  使DispatcherServlet对静态资源的请求转发到Servlet容器默认的Servlet上,而不是使用DispatcherServlet本身来处理此类请求
	 @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
		 configurer.enable();
    }
	 
  /*  @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
    	registry.addResourceHandler("/css/**").addResourceLocations("classpath:/css");
    	registry.addResourceHandler("/js/**").addResourceLocations("classpath:/js");
    	registry.addResourceHandler("/img/**").addResourceLocations("classpath:/img");
    }*/
    
	 
	 @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        super.configureMessageConverters(converters);
      
        FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
 
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        fastJsonConfig.setSerializerFeatures(
                SerializerFeature.PrettyFormat
        );
        fastConverter.setFastJsonConfig(fastJsonConfig);
        converters.add(fastConverter);
    }
	 
}

这是配置文件的解决办法

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
	<property name="maxUploadSize" value="100000"></property>
</bean>

前端使用的是百度的插件WebUploader 下载地址在github上(点击即可)

只需要引入

<link href="../../css/webuploader.css" rel="stylesheet" />
<script type="text/javascript" src="../../js/jquery-1.8.3.min.js"></script>
<script type="text/javascript" src="../../js/webuploader.min.js"></script>


<div class="form-group">
		<label for="recipient-name" class="control-label">头像:</label>
        <input type="hidden" class="form-control" id="image" name="image">
        <div><img style="width:100px;height:100px" id="imageEcho"/></div>
        <div id="chooseImg">选择头像</div>
</div>


<script>
		var uploader = WebUploader.create({
		    auto: true,
		    swf: '${ss }/js/Uploader.swf',
		    server: '${base}/movie/server/uploadImage.do',
		    duplicate: true,
		    pick: '#chooseImg',
		    accept: {
		        title: 'IMAGE',
		        extensions: 'gif,jpg,jpeg,bmp,png',
		        mimeTypes: 'image/png,image/jpeg'
		    }
		});
		uploader.on("uploadSuccess",function(file,response){
			if(response.success){
				$("#imageEcho").attr("src","${ss}"+response.obj);
				$("#image").val(response.obj);
			}else{
				alert(response.msg)
			}
		});
		</script>

到这里就会遇到另一个坑 就是点击按钮无反应

这是百度到解释 因为本人助攻后端 前端有些东西一笔而过不细究

后来查找原因发现它隐藏的Input和lable宽度width只有1px,height也是1px,基本点不到嘛。。查找webuploader源码头昏,还是在页面自己加上style解决省
事儿。

<style>  
	    #chooseImg  div:nth-child(2){width:100%!important;height:100%!important;}  
</style> 

效果图

终于解决了.......---->开心<---..........

以下是我上传图片的工具类

    /**
	 * 在Linux下的图片上传 读取的配置文件当做路径
	 * 
	 * @param request
	 * @param j
	 * @param createFilePath
	 *            保存路径
	 * @param saveImgPath
	 *            图片的 访问路径
	 * @return
	 */
	public static AjaxJson uploadImageLiunx(MultipartHttpServletRequest request, AjaxJson j, String createFilePath,
			String saveImgPath) {
		InputStream is = null;
		OutputStream os = null;
		try {
			// webuploader 获取文件的方式
			MultipartFile multipartFile = request.getFile("file");
			// 获取文件的名称
			String originalFilename = multipartFile.getOriginalFilename();
			// 截取文件的后缀名称
			String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
			// 使用当前时间作为文件名
			String fileName = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());

			// 读取配置文件下的路径
			PropertiesUtil p = new PropertiesUtil("amysky.properties");
			// 反斜杠(liunx)
			String fileUpload = p.read("fileUpload");
			// 创建文件夹
			File file = new File(fileUpload + createFilePath);

			String sep = System.getProperty("file.separator");
			if (!file.exists()) {
				file.mkdirs();
			}

			file = new File(fileUpload + createFilePath + sep + fileName + suffix);
			// 获取文件的输入流
			is = multipartFile.getInputStream();
			// 创建的输出流
			os = new FileOutputStream(file);
			copyFile(is, os);
			j.setSuccess(true);
			j.setMsg("上传成功");
			j.setObj(saveImgPath + File.separator + fileName + suffix);
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("系统繁忙,请稍后重试");
			e.printStackTrace();
		} finally {
			try {
				// 关流
				os.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				// 关流
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		return j;
	}

    /**
	 * 上传到window环境的图片
	 */
	public static AjaxJson uploadImageWindows(MultipartFile  multipartFile,HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		InputStream is = null;
		OutputStream os = null;
		try {
			// 获取文件名称
			String originalFilename = multipartFile.getOriginalFilename();
			// 获取文件的后缀
			String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
			// 使用现在的 时间作为图片的新名称
			String fileName = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());

			// 获取文件夹在Windows上的 真是文件路径 例如: upload文件夹
			String realPath = request.getServletContext().getRealPath("upload");
			// 创建保存图片的文件夹
			String path = realPath + File.separator ;
			// 不存在就创建
			File file = new File(path);
			if (!file.exists()) {
				file.mkdirs();
			}
			// 保存文件
			file = new File(path + File.separator + fileName + suffix);

			is = multipartFile.getInputStream();
			os = new FileOutputStream(file);
			// 拷贝文件
			copyFile(is, os);
			j.setSuccess(true);
			j.setObj("upload" + File.separator + fileName + suffix);
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("系统繁忙,请稍后重试");
			e.printStackTrace();
		} finally {
			try {
				os.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return j;
	}


	/**
	 * 文件拷贝
	 * 
	 * @param is
	 * @param os
	 * @throws IOException
	 */
	private static void copyFile(InputStream is, OutputStream os) throws IOException {
		byte[] b = new byte[1024];
		int len = 0;
		while ((len = is.read(b)) != -1) {
			os.write(b, 0, len);
		}
		os.flush();
	}

猜你喜欢

转载自blog.csdn.net/yinlell/article/details/83589003