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

导读:本篇文章讲解 基于Maven的图片上传(图片路径存储在数据库中),希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

前端代码:

<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("上传失败!");
        }
    }

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

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/96859.html

(0)
小半的头像小半

相关推荐

极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!