加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ajax+spring文件上传

发布时间:2020-12-16 00:26:36 所属栏目:百科 来源:网络整理
导读:1、js代码 $(function(){$('#upfileID').change(function(){$.ajaxFileUpload({ url: '/upload/image',type: 'post',secureuri: false,//一般设置为false fileElementId: 'upfileID',// 上传文件的id属性名 dataType: 'text',//返回值类型,一般设置为json、

1、js代码

$(function(){
	$('#upfileID').change(function(){
	$.ajaxFileUpload({
        url: '/upload/image',type: 'post',secureuri: false,//一般设置为false
        fileElementId: 'upfileID',// 上传文件的id属性名
        dataType: 'text',//返回值类型,一般设置为json、application/json
        success: function(data,status){  
        	//alert(data);
        	$('#imgSrc').val(data);
            $('#imgv').html('<img src="'+data+'" style="max-width:80px">');
            
        },error: function(data,status,e){ 
            alert(e);
        }
        });
	})
})

2、html代码

//引入ajaxFileUpload
<script type="text/javascript" src="ajaxfileupload.js"></script>
<input type="file" id="upfileID" name="upfile" class="can-file">

4、applicationContext.xml添加以下配置

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />

5、java代码
@RequestMapping("image")
	public void image(HttpServletRequest request,HttpServletResponse response,@RequestParam("upfile") MultipartFile upfile){
		String originalFilename = upfile.getOriginalFilename();
//		System.out.println("文件原名: " + originalFilename);
//		System.out.println("文件名称: " + upfile.getName());
//		System.out.println("文件长度: " + upfile.getSize());
//		System.out.println("文件类型: " + upfile.getContentType());
		
		String realPath = request.getSession().getServletContext().getRealPath("/resources/upload");
		File file = new File(realPath);
		if(!file.exists()) file.mkdirs();

		try {
			upfile.transferTo(new File(realPath,originalFilename));
		} catch (IOException e) {
			e.printStackTrace();
		}
		//设置响应给前台内容的数据格式
//		response.setContentType("text/plain; charset=UTF-8");
		renderText(request.getContextPath() + "/resources/upload/" +  originalFilename,response);

	}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读