java 上传文件到服务器+回显图片,页面可以不选择文件,文件input可以为空

  • Post author:
  • Post category:java


java 上传文件到服务器+回显图片,文件input可以为空

common-fileupload依赖

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

//导入表单js

<script src="jquery.form.js"></script>

//页面

form表单记得加上 enctype=“multipart/form-data”

.pic-div {
        display: inline-block;
        float: left;
        margin-left: 8px;
        margin-bottom: 10px;
        margin-top: 10px;
    }
    .pic-show {
        max-width: 500px;
        max-height: 500px;
        display: inline-block;
        float: left;
    }
<tr>
	<td class="lable_td">上传图片:</td>
	<td>	
		<input style="display: none" type="file" id="file" name="image_path" accept="image/*,.pdf" multiple onchange="imgOnLoad();" />
		<input id = "buttonpic"  type="button" onclick="imgUpload();" value = "选择图片" />
		<span  id="imgdiv"></span>
	</td>
</tr>
//选择文件
function imgUpload() {
 $("#file").click();
}
//将图片名称显示到页面上
function imgOnLoad(){
    var reads = new FileReader();
    var f = document.getElementById('file').files[0];
    reads.readAsDataURL(f);
    var index=f.name.lastIndexOf("\.");
    var hz=f.name.substring(index+1,f.name.length);
    if(hz.indexOf('pdf')>-1){
    	 reads.onload = function(e) {
    	        let li = "<div class='pic-div'>" +
    	            "<a class='pic-show' id=\"filePic\" href='"+this.result+"' >"+f.name+"</a>"+
    	            "</div>";
    	        $("#imgdiv").html(li);
    	    };
    }else{
    	reads.onload = function(e) {
            let li = "<div class='pic-div'>" +
                "<img class='pic-show' id=\"filePic\" src='"+this.result+"' onclick='scalingPic(\""+this.result+"\")'>"+
                "</div>";
            $("#imgdiv").html(li);
        };
    }
}

后台代码

@RequestMapping(value="/addPreventionCard")
@ResponseBody
public String addPreventionCard(HttpServletRequest request,HttpServletResponse response,
		@RequestParam HashMap<String,Object> map) {
	MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
	List<MultipartFile> uploadFiles= multipartRequest.getFiles("image_path");
	Map<String, Object> resultmap = new HashMap<String, Object>();
	//可以添加业务代码
	
	try {
		if (uploadFiles.size() > 0) {
			MultipartFile mlfile = uploadFiles.get(0);
			// 定义上传路径
			String path = request.getSession().getServletContext()
					.getRealPath("/dzzh" + File.separator + "mbkimages");
			//如果文件夹不存在,自动创建文件夹
			File dirFile = new File(path);
	        if (!dirFile.exists()) {
	            dirFile.mkdirs();//创建文件夹
	        }
			// 获得原文件名
			String oldFileName = mlfile.getOriginalFilename();
			// 获得原文件后缀名
			String prefix = FilenameUtils.getExtension(oldFileName);
			// 判断文件大小
			long filesize = 50000000;
			if (mlfile.getSize() > filesize) {
				resultmap.put("resultcode", "0");
				resultmap.put("resultmsg", "文件过大");
			} else if (prefix.equalsIgnoreCase("jpg")
					|| prefix.equalsIgnoreCase("png")
					|| prefix.equalsIgnoreCase("gif")) {
					// 搞一个新的文件名
					String uuid = UUID.randomUUID().toString().replaceAll("-", "").toUpperCase();
					String newFileName = uuid + ".jpg";
					// 封装数据
					File targetFile = new File(path, newFileName);
					//上传
					mlfile.transferTo(targetFile);
					resultmap.put("resultcode", "");
					resultmap.put("resultmsg", "上传成功");
			} else {
				resultmap.put("resultcode", "0");
				resultmap.put("resultmsg", "文件类型不正确");
			}
		}
	} catch (IllegalStateException e) {
		e.printStackTrace();
	} catch (IOException e) {
		e.printStackTrace();
	}
	//返回前台数据
	return JSON.toJSONString(resultmap);
}

第一次写,主要想记录一下代码,有不对的地方欢迎指出。



版权声明:本文为weixin_44625066原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。