SpringMvc+Ajax 上传图片

因为项目做提交的时候都用的ajax,需要加上上传图片功能,并且回显,就使用了Jquery的ajaxForm来提交。

后端使用SpringMVC自带的multipartFile

1.引入commons-fileupload.jar

<dependency>
	<groupId>commons-fileupload</groupId>
	<artifactId>commons-fileupload</artifactId>
	<version>1.3.1</version>
</dependency>

2.在spring配置文件中声明使用multipartResolver解析上传的文件

<bean id="multipartResolver"
           class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
            <property name="defaultEncoding" value="UTF-8" />
             <!-- 上传文件大小限制 -->
            <property name="maxUploadSize" value="10240000" />
         </bean>

其他属性:

      -defaultEncoding 编码方式
-maxInMemorySize 最大缓存

3.html

<div class="row">
   <label class="col-sm-3 control-label"></label>
   <div class="col-sm-7">
   <img src="" alt="" width="200px" id="showPic">
   </div>
</div>
<input type="hidden" class="form-control" id="bannerUri">
<div class="row">
   <label class="col-sm-3 control-label">上传图片</label>
   <div class="col-sm-7">
      <form action="" enctype="multipart/form-data" method="post" id="uploadForm" >
         <input type="file" name="picFile">
         <input type="submit" class="btn btn-primary"  value="上传" id="upButton"/>
      </form>
   </div>
</div>


4.js

引入
jquery.form.js

$('#upButton').on('click', function() {
	$('#uploadForm').on('submit', function() {
		$("#uploadForm").ajaxSubmit({
			type: "POST",
			url:__path+"/banner/photoUpload",
			dataType: "json",
			success: function(data){
				if(data.msg == 'SUCCESS'){
					$("#showPic").attr("src", data.url);
					$("#bannerUri").val(data.url);
				}
			}
		});
		return false; // 阻止表单自动提交事件
	});
});



5.JAVA代码


  /**
     * 图片文件上传
     */
    @ResponseBody
    @RequestMapping(value = "/photoUpload",method = RequestMethod.POST)
    public String photoUpload(MultipartFile picFile) throws IllegalStateException, IOException {
        Map map = new HashMap();
        if (picFile == null) return null;
        Properties properties = null;
        String path = null;   // 文件路径
        String type = null;// 文件类型
        String fileName = picFile.getOriginalFilename();// 文件原名称
        try{
            properties = PropertiesUtil.getProperties("/props/appConfig.properties");
        }catch (Exception ex){
            ex.printStackTrace();
        }
        // 判断文件类型
        type = fileName.indexOf(".") != -1 ? fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()) : null;
        if (type == null) return null;// 判断文件类型是否为空
        if ("gif".equalsIgnoreCase(type) || "png".equalsIgnoreCase(type) || "JPG".equalsIgnoreCase(type)) {
            // 项目在容器中实际发布运行的根路径
            String realPath = PropertiesUtil.getPropVal(properties, "picPath");   //服务器中存放的文件路径
            String urlPath = PropertiesUtil.getPropVal(properties, "picUrl");   //文件的url地址
            // 自定义的文件名称 原名+随机数Md5+当前时间
            Random random = new Random();
            String trueFileName = MD5Util.makeMD5(fileName + random.nextInt(100)) + System.currentTimeMillis() + "." + type;
            // 设置存放图片文件的路径
            path = realPath + trueFileName;

            System.out.println("存放图片文件的路径:" + path);
            // 转存文件到指定的路径
            picFile.transferTo(new File(path));
            System.out.println("文件成功上传到指定目录下");

            map.put("msg", "SUCCESS");
            map.put("url", urlPath + trueFileName);

            return JSONUtil.toJSONString(map);

        } else {
            System.out.println("不是我们想要的文件类型,请按要求重新上传");
        }
        return null;
    }





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值