使用jquery无刷新上传图片,可用于头像预览功能

邓毅
2023-12-01
</pre><p><span style="font-size:14px;">html:</span></p><p></p><pre name="code" class="html"><input type="file" name="path" id="up-fileboxs"/>

<img src="<cms:getProjectBasePath/>resources/images/gravatar.gif" alt="" width="100" height="100" class="avatar">

jquery:


$('#up-filebox').fileupload({
        url: "<cms:getProjectBasePath/>user/upload",
        disableImageResize: /Android(?!.*Chrome)|Opera/
            .test(window.navigator.userAgent),
        maxFileSize: 2*1024*1024,
        maxNumberOfFiles:1,
        paramName:'files',
        acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i
    }).bind('fileuploaddone', function (e, data) {
    	$('.avatar').attr('src','<cms:getProjectBasePath/>'+data.result.data);
  	$('#avatar_form').find('input[name="path"]').val(data.result.data);
    });


Java:使用springMVC

<pre name="code" class="java">@RequestMapping(value = { "/upload" }, method = { RequestMethod.POST })
	@ResponseBody
	public AjaxResult upload(HttpServletRequest request){
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
		if (multipartResolver.isMultipart(request)) {
			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;

			Iterator<String> iter = multiRequest.getFileNames();
			while (iter.hasNext()) {

				// 由CommonsMultipartFile继承而来,拥有上面的方法.
				MultipartFile file = multiRequest.getFile(iter.next());
				if (file != null) {
					String realPath = FileUtil.getUploadPath(request),dailyPath=FileUtil.getDailyPath();
					realPath+=dailyPath;
					FileUtil.createDir(new File(realPath));//创建目录
					File attachFile=FileUtil.createTimeNewFile(realPath, file.getOriginalFilename());//创建一个新文件
					try {
						FileUtils.copyInputStreamToFile(file.getInputStream(), attachFile);
						String savePath="/upload"+dailyPath+attachFile.getName();
						return AjaxResult.dataResult("上传成功!", savePath);
					} catch (IOException e) {
						log.error("文件保存失败!",e);
					}
				}
			}
		}
		return AjaxResult.errorResult("没有上传文件");
	}	


 

需在springMVC配置中配置

<!-- SpringMVC上传文件时,需要配置MultipartResolver处理器 -->
	<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<property name="defaultEncoding" value="utf-8" />
		<property name="maxUploadSize" value="10485760000" />
		<property name="maxInMemorySize" value="40960" />
	</bean>


 类似资料: