ajax实现点击图片打开文件上传和图片加载失败如何显示指定图片

本文介绍了一个使用Ajax实现的文件上传功能,特别是针对图片的处理。通过JavaScript和jQuery,点击图片可以触发文件选择,并在上传过程中处理图片加载失败的情况,设定默认显示‘未上传.jpg’作为替代。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.文件上传前端代码
这里设置了文件上传框隐藏,点击图片会显示出来,在这里用的是上传图片并显示出来,其他类型文件也可,注意:ajax请求尽量用post,get类型有大小限制。

<img class="card-media" style="width:16rem;height:16rem" 
     src="<%=basePath%>static/images/userImage/测试.jpg" 
     onclick="openuploadMethod('${st.wiNum}')" alt="未上传头像" 
      onerror="javascript:this.src='<%=basePath%>static/images/userImage/未上传.jpg'" />
      	<div class="card-body" id="upbutton" style="display:none">
      		<form id="fileform" method="post" enctype="multipart/form-data">
			<input id="upload" name="uploadfile" style="color:blue"  type="file" >
      		<button  class="icon-cloud-upload" onclick="uploadMethod()">点击上传</button>
			</form>	
      	 </div>

其中οnerrοr="javascript:this.src=’<%=basePath%>static/images/userImage/未上传.jpg’"是图片加载失败显示图片
//打开文件上传界面

//打开文件上传
function openuploadMethod(wNum){
		document.getElementById('upload').click();
		$("#upbutton").show();
	}
//上传头像
	function uploadMethod(){
		var form = new FormData(document.getElementById("fileform"));
	    $.ajax({
	        type:"post",
	        url:"http://localhost:8080/ssm/worker/upload",
	        data:form,
	        processData:false,
	        contentType:false,
	        async: false,
	        dataType:'text',
	        success:function(data){
	                if(data>0){
	                	alert("上传成功")
						window.location.reload();
	                	return;
	                }
	                alert("请选择文件")
	        }
	    });
	}
**2.后端代码**

```java
/**
	 * 上传图片
	 */
	@PostMapping("/upload")
	@ResponseBody
	public int testupload(@RequestParam("uploadfile") MultipartFile file,HttpServletRequest request) throws IllegalStateException, IOException{
        if(!file.isEmpty()) {
        	//上传文件路径
        	String classpath = this.getClass().getResource("/").getPath().replaceFirst("/", "");
        	String path = classpath.replaceAll("WEB-INF/classes/", "")/*后面部分是工程文件目录,自定义*/+"static/images/userImage/";
            //上传文件名
            //String filename = file.getOriginalFilename();/*这个是上传文件的原文件名*/
            //自定义生成文件名
            String filename=测试.jpg
            File filepath = new File(filename);
            //判断路径是否存在,如果不存在就创建一个
            if (!filepath.getParentFile().exists()) {
                filepath.getParentFile().mkdirs();
            }
            //上传
            file.transferTo(filepath);
            return 1;
        } else {
            return 0;
        }
    }

完成!!!下次再弄文件下载代码

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值