Java上传图片并查看

Java上传图片并查看

 

一.配置tomcat:

在tomcat的server.xml配置文件的<Host></Host>标签下加以下内容:

<Context debug="0" docBase="E:/images" path="/showImages" reloadbale="true"/>
<Context docBase="projectName" path="/projectName" reloadable="true" source="org.eclipse.jst.jee.server:projectName"/>

 

二.编写上传图片、解析图片路径代码:

//上传照片
	public String uploadImage() {
		// 获取当前用户
        SysUserAccounts sysUserAccounts = SessionUtil.getSysUserAccounts(getSession());
        cusStdCustarchives = customerArchivesBL.getCustomerArchivesByAccountId(sysUserAccounts.getRelationId());
        try {
        	// 初期化信息提示
            msg = "";
            String fileName;
            boolean flg = false;
            // 定义显示的消息
            StringBuilder uploadMsg = new StringBuilder();
            if (uploadImage != null) {
                for (int k = 0; k < uploadImage.size(); k++) {
                    if (uploadImage.get(k) == null || uploadImage.get(k).equals("")) {
                        uploadMsg.append("上传文件不能为空,请检查! <br>");
                        break;
                    } else {
                        flg = true;
                    }
                }
            } else {
                uploadMsg.append("上传文件不能为空,请检查!<br>");
            }
            if (flg) {
                // 把得到的文件的集合通过循环的方式读取处理
                for (int i = 0; i < uploadImage.size(); i++) {
                    String time = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
                    // 获取上载文件的文件名称
                    fileName = uploadImageFileName.get(i);
                    // 获取上载文件的扩展名
                    String fileNameExtension = fileName.substring(fileName.lastIndexOf(".")).toLowerCase();
                    // 文件格式CHECK
                    if (fileNameExtension.equals(".jpg") || fileNameExtension.equals(".gif")
                        || fileNameExtension.equals(".png")) {
                        if (fileName != null) {
                            // 存放在盘下面的文件名称
                            String fileNmae2 = time + fileNameExtension;
                            // 把上传的文件写到指定的路径中
                            File filepath = new File(getText("filepath") + File.separator + cusStdCustarchives.getRelationId());
                            // 如果指定的路径没有就创建
                            if (!filepath.exists()) {
                                filepath.mkdirs();
                            }
                            // 数值格式化
                            DecimalFormat df = new DecimalFormat("#.00");
                            ins = new FileInputStream(uploadImage.get(i));
                            // 文件大小不能大于10M
                            if (ins.available() < 1024 * 1024 * 5) {
                                List<CusStdFile> checkList = fileBL.getUploadFileCheckByCustomerRelationId(cusStdCustarchives.getRelationId(), fileName);
                                if (checkList.size() < 1) {
                                    double result = (double) ins.available() / 1024;
                                    BigDecimal filesize = new BigDecimal(df.format(result));
                                    // 添加文件到数据库中
                                    CusStdFile uploadFile = new CusStdFile();
                                    uploadFile.setClassifyId(cusStdCustarchives.getRelationId());
                                    uploadFile.setModeId(modeId);
                                    uploadFile.setStatus(1);
                                    uploadFile.setFileName(fileName);
                                    uploadFile.setUniqueName(fileNmae2);
                                    uploadFile.setFileurl(filepath.getAbsolutePath());
                                    uploadFile.setFileSize(filesize);
                                    uploadFile.setFileType(fileType);
                                    uploadFile.setCreater(sysUserAccounts.getUsername());
                                    uploadFile.setCreateTime(new Date());
                                    fileBL.savaFile(uploadFile);
                                    // list集合通过get(i)的方式来获取索引
                                    FileUtils.copyFile(uploadImage.get(i), new File(filepath + "/", fileNmae2));
                                    uploadMsg.append("文件: " + fileName + " 上传成功  <br>");
                                } else {
                                    uploadMsg.append(fileName + "  已存在,请更换文件名再上传! <br>");
                                }
                            } else {
                                uploadMsg.append("文件大小大于5M,请检查 !<br>");
                            }
                        }
                    } else {
                        uploadMsg.append("文件格式不正确,请检查!<br>");
                        break;
                    }
                }
            }
            // /显示上载文件的操作成功消息
            msg = uploadMsg.toString();
            uploadImage = null;
            return SUCCESS;
        } catch (Exception e) {
            return ERROR;
        }
        
	}

 

三.jsp:

<form id="uploadFileform"
    action="$!{request.contextPath}/loan/uploadImage" method="post"
    enctype="multipart/form-data" >
    <center>
      <label id="Header" cssClass="HeaderText" value="图片上传" />
      <hr style="size: 1" />
      <p id="FileList">
	<input id="uploadImage" value="2" type="file" name="uploadImage" size="50" />
	<img src="$!{request.contextPath}/images/lend/close.png" class="closea">
      </p>
					
      <hr style="size: 1" />
      <p>温馨提示:只允许上传.jpg .gif .png 后缀的图片</p>
      <p style="color:green;">(请务必上传真实证件照片或图片 否则不会通过认证)</p>
      <p>
       <input class="btn btn-primary" type="button" value="继续添加" onclick="newFile()" />
       <input class="btn btn-primary" type="button"  value="上传图片" onclick="uploadImages();"/>
      </p>
      <hr style="size: 1" />
      </center>
      <p align="center">
        <span class="GbText" style="width: 100%; color: red;"></span>
      </p>
      <input type="hidden"  name="fileType" id="codeID" />
      <input type="hidden" name="modeId" value="Obj0000009" />
</form>

 

四.js脚本:

<script>
		
		function deleteNode(obj) {
		 var parent = obj.parentNode;
         if(parent){
         	parent.remove();
         }
		}
	
		function newFile() {
			$("#FileList").append('<p><input id="uploadImage" value="" type="file" name="uploadImage" size="50" /><a href="javascript:void(0);" onclick="deleteNode(this)" ><img src="$!{request.contextPath}/images/lend/close.png" class="closea"></a></p>');
		}
		
		function setCode(code,title) {
			$("#uploadTitle").html(title);
			$("#FileList").html('<p><input id="uploadImage" value="" type="file" name="uploadImage" size="50" /><a href="javascript:void(0);" onclick="deleteNode(this)" ><img src="$!{request.contextPath}/images/lend/close.png" class="closea"></a></p>');
			$("#codeID").val(code);
		}
		
		function showImage(imageUrl,title) {
			$("#authImage").attr("src", imageUrl);		
			$("#imageTitle").html(title);		
		}
	
		function uploadImages() {
    		var str = $("#uploadImage").val();
			if(str.length!=0){
				var reg = ".*\\.(jpg|png|gif|JPG|PNG|GIF)";
				var r = str.match(reg);
				if(r == null){
					alert("对不起,您的图片格式不正确,请重新上传");
				}
				else {
					if(window.ActiveXObject) {
    					var image=new Image();
      					image.dynsrc=str;
    					if(image.fileSize>5243000){
    						alert("上传的图片大小不能超过5M,请重新上传");
    						return false;
    					}
    				}
    				else{
    					var size = document.getElementById("uploadImage").files[0].size;
    					if(size>5243000) {
    						alert("上传的图片大小不能超过5M,请重新上传");
    						return false;
    					}
    				}
					$('#uploadFileform').submit();
				}
			}
			else {
				alert("请先上传图片");
			}
    	}

		
    </script>

 

 

 

五.页面上显示图片:

<img src="showImages/2014070005656/20140724100548048.png" />

 

 

六.图片存储位置:

Java上传图片并查看
 

 

 

七.网站界面:

Java上传图片并查看
 

你可能感兴趣的:(java,image,图片上传)