java+html+js上传图片到服务器对应文件夹中

2022-07-29,,,,

先看效果

实现步骤

按照步骤完成后,可自行debugger进行适合自己业务的修改

1.html写入

<tr>
	<td class="tdstyle">上传图片</td>
	<td>
	    <img id="image" src=""  style="width: 300px; height: 200px;display: block;"/>
		<span><input type="file" name="file" id="file" onchange="selectImage(this);"></span>
		<button onclick="importWeldingMachine()">保存</button>
	</td>
</tr>

2.前端js

var imgdata = '';
//选择文件
function selectImage(obj){
	var f=$(obj).val();
    if(f == null || f ==undefined || f == ''){
        document.getElementById('image').src = "";
        $("#image").show();
        return false;
    }
    if(!/\.(?:png|jpg|bmp|gif|PNG|JPG|BMP|GIF)$/.test(f)){
        alert("类型必须是图片(.png|jpg|bmp|gif|PNG|JPG|BMP|GIF)");
        $(obj).val('');
        return false;
    }
    imgdata = new FormData();
    $.each($(obj)[0].files,function(i,file){
        imgdata.append('file', file);
    });
    if(!file.files || !file.files[0]){
        return;
    }
    //将上传的图片显示到页面
    var reader = new FileReader();
    reader.onload = function(evt){
    	$("#image").show();
        document.getElementById('image').src = evt.target.result;
        uploadfile = evt.target.result;
    }
    reader.readAsDataURL(file.files[0]);
}
var imageurl = "";
//点击上传
function importWeldingMachine() {
    var file = $("#file").val();
	$.ajax({
            type : "post",
            async : false,
            url : "ActualWater/uploadimage.do",
            data : imgdata,
            cache : false,
            contentType : false, //不可缺
            processData : false, //不可缺,设置为true的时候,ajax提交的时候不会序列化 data,而是直接使用data
            dataType : "json", //返回数据形式为json  
            success : function(result) {
            	result=JSON.parse(result);
                if (result) {
                    if (!result.success) {
                        imageurl = "";
                        $.messager.show({title : 'Error',msg : result.errorMsg});
                    } else {
                        imageurl = result.imgurl;
                        //上传图片后,进行保存入库图片信息操作
                    }
                }
            },
            error : function(errorMsg) {
                alert("数据请求失败,请联系系统管理员!");
            }
    });
}

3.controller层

/**
	 * 图片上传到服务器文件夹中
	 * @param 
	 * @return imgurl图片路径,success接口状态
	 */
	@RequestMapping("/uploadimage")
    @ResponseBody
    public String uploadPicture(@RequestParam(value = "file", required = false) MultipartFile file,
            HttpServletRequest request, HttpServletResponse response) {
        JSONObject obj = new JSONObject();
        File targetFile = null;
        String url = "";// 返回存储路径
        String fileName = file.getOriginalFilename();// 获取文件名加后缀
        if (fileName != null && fileName != "") {
            //文件存储位置
            ServletContext scontext = request.getSession().getServletContext();
            // 获取绝对路径
            String path = scontext.getRealPath("/") + "UpLoadFile/imageFile";
            String lastname = fileName.substring(fileName.lastIndexOf("."), fileName.length());//文件后缀
            fileName = new Date().getTime() + "_" + new Random().nextInt(1000) + lastname;//当前时间+随机数=新的文件名
            // 如果文件夹不存在则创建
            File pathfile = new File(path);
            if (!pathfile.exists()) {
                pathfile.mkdirs();
            }
            // 将图片存入文件夹
            targetFile = new File(path, fileName);
            try {
                // 将上传的文件写到服务器上指定的文件。
                file.transferTo(targetFile);
                obj.put("success", true);
                url = fileName;//保存路径,便于后续存入数据库
            } catch (Exception e) {
                e.printStackTrace();
                obj.put("success", false);
                obj.put("errorMsg", e.getMessage());
            }
        }
        obj.put("imgurl", url);
        return obj.toString();
    }

完成

本文地址:https://blog.csdn.net/qq_43953273/article/details/109243746

《java+html+js上传图片到服务器对应文件夹中.doc》

下载本文的Word格式文档,以方便收藏与打印。