基于Maven的图片上传(图片路径存储在数据库中)

前端代码:

<input type="file" id="file" name="file"/>

使用ajax将其传给后台(ajax代码):


```css
file.onchange = function(){
	var formData = new FormData();
     var temp = file.files[0];
     if (temp){
                formData.append('file',temp)
                img.src = window.URL.createObjectURL(temp)
                $.ajax({
                    url:"/uploadImg/"+id,
                    type:"POST",
                    data: formData,
                    dataType : "json",
                    processData: false, // 告诉jQuery不要去处理发送的数据
                    contentType: false, // 告诉jQuery不要去设置Content-Type请求头
                    success: function(result){
                        //alert(result);
                        window.location.reload();
                    }
                });
            }

后台Java代码:


```java
@RequestMapping(value = "/uploadImg/{id}", method = RequestMethod.POST)
    public String upload(@RequestParam("file")MultipartFile file,Model model,
    		@PathVariable("id") int id,
            HttpServletRequest request) {
    	if (file.isEmpty()) {
            return "上传失败,请选择文件";
        }
        String fileName = file.getOriginalFilename();
        String newName = null;
        System.out.println(fileName);
     // 生成uuid作为文件名称
     	String uuid = UUID.randomUUID().toString().replaceAll("-", "");
     	/*// 获得文件类型(可以判断如果不是图片,禁止上传)
     	String contentType = user.getFile().getContentType();*/
     	// 获得文件后缀名
     	String suffixName = fileName
     					.substring(fileName.indexOf("/") + 1);
     	// 得到 文件名
     	newName = uuid + "." + suffixName;
        File dest = null;
        String path = null;
        String os = System.getProperty("os.name");
        System.out.println(os);
        if (os.toLowerCase().startsWith("win")) {
            path = "E:"+File.separator+"test"+File.separator;
            System.out.println(path);
            dest= new File(path + newName);
        }else {
            path = "/webapps/img/";
            dest= new File(path + newName);
        }
        model.addAttribute("src","img/"+newName);
		try {
            file.transferTo(dest);
            //把评论插入数据库
            Comment comment=new Comment();
            comment.setImages(newName);//此处只给出了images属性
            commentMapper.insert(comment);
            return JSON.toJSONString("上传成功!");
        } catch (IOException e) {
        	return JSON.toJSONString("上传失败!");
        }
    }

此时,我们便可以进行图片上传了!

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值