zoukankan      html  css  js  c++  java
  • jsp传中文,上传图片

    1 html 直接传参 jsp页面

    <%@ page contentType="text/html;charset=UTF-8" language="java"  pageEncoding="UTF-8"  %>

    <mata http-equiv=”content-type” content=”text/html; charset=utf-8”/>

    var Lxlmc  = "<%=java.net.URLDecoder.decode(request.getParameter("xlmc"),"UTF-8")%>";//linux
    var xtxh  = "<%=System.getProperty("os.name").toLowerCase()%>";//win

    if(xtxh.substring(0,3)!="win"){
            xlmc = Lxlmc;
        }

    2 文件分隔符linux与windows不同,用System.getProperty("file.separator")统一

    	private static final long serialVersionUID = -6525414170411696287L;
    	private static final String updpathdir = System.getProperty("file.separator")+"public"+System.getProperty("file.separator")+"images"+System.getProperty("file.separator")+"upload"+System.getProperty("file.separator");
    	private String filedir="zhct";//文件所在文件夹
    	private String name;//图片名字
    	private String suffix="png";//图片扩展名
    	private File file;//上传单个文件
    	private int width = 200;
    	private int height = 160;
    	private List<MultipartFile> multiFiles;//上传多个文件
    	private OrderManagerInf orderManager;
    	private int id;
    	private String rq;
    	
    
    	//图片列表
    	public String getImgs() throws Exception {
    		HttpServletRequest request = ServletActionContext.getRequest();
    		String realpath = request.getSession( ).getServletContext( ).getRealPath( "/" )+updpathdir+filedir;
    		String[] fiename = null;//name存储file文件夹中的文件名 
    		List<String> list = new ArrayList<>();
    		File newfile = new File(realpath);
    	    if(!newfile.exists()){
    	    	newfile.mkdirs();//如果目录不存在,新建
    	    }else{
    	    	if (newfile.isDirectory()){//判断file是否是文件目录 若是返回TRUE  
    	    		fiename = newfile.list(); 				
    	    		Collections.addAll(list, fiename);
    	    		Collections.sort(list,Collator.getInstance(java.util.Locale.CHINA));
    	        } 
    	    }
    		request.setAttribute("random", System.currentTimeMillis());
    	    request.setAttribute("filedir", filedir);
    	    request.setAttribute("fienames", list);
    		return "picList";
    	}
    	
    	
    	//上传图片,png,透明
    	public void updPngFile() throws Exception {//png,jpg图片,压缩,背景白的
    		HttpServletRequest request = ServletActionContext.getRequest();
    		HttpServletResponse response = ServletActionContext.getResponse();
    		response.setContentType("text/html;charset=utf-8");
    		PrintWriter out = response.getWriter();
    		String realpath = request.getSession( ).getServletContext( ).getRealPath( "/" )+updpathdir+filedir;
    		Map<String, Object> re = new HashMap<>();
    		try{
    			if(file == null){
    				throw new Exception(I18nUtil.getText("basicModule.zhct.pic.notexit", session.getAttribute("appLang")+""));
    			}
    			BufferedImage bi1 = ImageIO.read(file);
    			if(bi1 == null){ 
    				throw new Exception(I18nUtil.getText("basicModule.zhct.pic.geshi", session.getAttribute("appLang")+""));
    			}
    			if(file.length()>=500000){
    				throw new Exception(I18nUtil.getText("basicModule.zhct.pic.size", session.getAttribute("appLang")+""));
    			}
    			File newfile = new File(realpath);
    		    if(!newfile.exists()){
    		    	newfile.mkdirs();//如果目录不存在,新建
    		    }
    		    String fileName = name+".png";
    		    String srcImgPath = realpath+System.getProperty("file.separator")+fileName;  //存成png格式
    		    FileInputStream is = new FileInputStream(file);
    		    BufferedImage sourceImg =ImageIO.read(new FileInputStream(file)); 
    		    int width = sourceImg.getWidth();
    		    int height = sourceImg.getHeight();
    		    //获取图片流
    		    ImageInputStream iis = ImageIO.createImageInputStream(is);
    		    Iterator<ImageReader> it = ImageIO.getImageReadersByFormatName(suffix); 
    		    ImageReader reader = it.next();
    		    reader.setInput(iis,true) ;       
    		    ImageReadParam param = reader.getDefaultReadParam();
    		    Rectangle rect = new Rectangle(0,0,width,height);
    		    param.setSourceRegion(rect);
    		    BufferedImage bi = reader.read(0,param); 
    		    ImageIO.write(bi, suffix, new File(srcImgPath));  
    	        re.put("fileName", fileName);
    	        re.put("status", "success");
    		}catch (Exception e) {
    			logger.info("updPngFile fail...", e);
    			re.put("status", "exception");
    			re.put("message", e.getMessage());
    		}	
            // 写入列表 查询结果
         	out.println(JSON.toJSONString(re));
         	out.flush();
         	out.close();	
    	}
    	//上传图片
    	public void updFile() throws Exception {//png,jpg图片,压缩,背景白的
    		HttpServletRequest request = ServletActionContext.getRequest();
    		HttpServletResponse response = ServletActionContext.getResponse();
    		response.setContentType("text/html;charset=utf-8");
    		PrintWriter out = response.getWriter();
    		String realpath = request.getSession( ).getServletContext( ).getRealPath( "/" )+updpathdir+filedir;
    		Map<String, Object> re = new HashMap<>();
    		try{
    			if(file == null){
    				throw new Exception("文件不存在!");
    			}
    			BufferedImage bi1 = ImageIO.read(file);
    			if(bi1 == null){ 
    				throw new Exception("此文件不为图片文件");
    			}
    			File newfile = new File(realpath);
    		    if(!newfile.exists()){
    		    	newfile.mkdirs();//如果目录不存在,新建
    		    }
    		    Image srcFile = ImageIO.read(file);   
    	        String fileName = name+".png";
    	        String srcImgPath = realpath+System.getProperty("file.separator")+fileName;  //存成png格式
    	        BufferedImage buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);  
    	        Graphics2D graphics = buffImg.createGraphics();  
    	        graphics.setBackground(new Color(255,255,255));  
    	        graphics.setColor(new Color(255,255,255));  
    	        graphics.fillRect(0, 0, width, height);  
    	        graphics.drawImage(srcFile.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0, null);    
    	        ImageIO.write(buffImg, "jpg", new File(srcImgPath));  
    	        re.put("fileName", fileName);
    	        re.put("status", "success");
    		}catch (Exception e) {
    			logger.info("updFile fail...", e);
    			re.put("status", "exception");
    			re.put("message", e.getMessage());
    		}	
            // 写入列表 查询结果
         	out.println(JSON.toJSONString(re));
         	out.flush();
         	out.close();
    	}
    	
    	//删除图片
    	public void delFile() throws Exception {
    		HttpServletRequest request = ServletActionContext.getRequest();
    		HttpServletResponse response = ServletActionContext.getResponse();
    		response.setContentType("text/html;charset=utf-8");
    		PrintWriter out = response.getWriter();
    		String realpath = request.getSession( ).getServletContext( ).getRealPath( "/" )+updpathdir+filedir;
    		Map<String, Object> re = new HashMap<>();
    		try{
    			String srcImgPath = realpath+System.getProperty("file.separator")+name;  //存成png格式
    			File f = new File(srcImgPath);
    	        if(f.exists()){
    	        	f.delete();
    	        }
    	        re.put("status", "success");
    		}catch (Exception e) {
    			logger.info("delFile fail...", e);
    			re.put("status", "exception");
    			re.put("message", e.getMessage());
    		}		
            // 写入列表 查询结果
         	out.println(JSON.toJSONString(re));
         	out.flush();
         	out.close();
    	}
    	
    	//改变图片名称
    	public void editFile() throws Exception {
    		HttpServletRequest request = ServletActionContext.getRequest();
    		HttpServletResponse response = ServletActionContext.getResponse();
    		response.setContentType("text/html;charset=utf-8");
    		PrintWriter out = response.getWriter();
    		String realpath = request.getSession( ).getServletContext( ).getRealPath( "/" )+updpathdir+filedir;
    		Map<String, Object> re = new HashMap<>();
    		try{
    			String oldPath = realpath+System.getProperty("file.separator")+name;  //存成png格式
    			File f = new File(oldPath);
    			String newPath = realpath+System.getProperty("file.separator")+request.getParameter("newName")+".png";
    			f.renameTo(new   File(newPath));   //改名    
    	        re.put("status", "success");
    		}catch (Exception e) {
    			logger.info("editFile fail...", e);
    			re.put("status", "exception");
    			re.put("message", e.getMessage());
    		}		
            // 写入列表 查询结果
         	out.println(JSON.toJSONString(re));
         	out.flush();
         	out.close();
    	}
    
    <%@ page language="java" contentType="text/html; charset=UTF-8"
    	pageEncoding="UTF-8"%>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
    <%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %> 
    <c:set var="ctx" value="<%=request.getContextPath()%>" />
    <!DOCTYPE html>
    <html>
    <head>
    <%@ include file="/jsp/meta.jsp"%>
    <link rel="stylesheet" type="text/css" href="${ctx}/public/extjs/ExtGrid.css" />
    <script type="text/javascript" src="${ctx}/public/js/jquery.js"></script>
    <script type="text/javascript" src="${ctx}/public/jQueryUI/jquery-ui.min.js"></script>
    <script type="text/javascript" src="${ctx}/public/js/ajaxfileupload.js"></script>
    <script type="text/javascript" src="${ctx}/js/locale/basicModule/zhct/menu_${appLang}.js"> </script>
    <script>
    window.onload = function() { 
    	hideLeft();	
    };
    function uploadFile(obj) {  	
    	var file = $("#file").val();
    	var name = getFileName(file);
    	var index1=file.lastIndexOf(".");  
    	var index2=file.length;
    	var suffix=file.toLowerCase().substring(index1+1,index2);//后缀名 
    	if(suffix!="png" & suffix!="jpg"  & suffix!="jpeg"){
    		Wg.alert(basicModule_zhct.resourceBundle.Error.geshi);
    		return false;
    	}
    	
    	var reg = /[\u4e00-\u9fa5]/g;
    	if(reg.test(name)){
    		Wg.alert(basicModule_zhct.resourceBundle.Error.ischar);
    		return false;
    	}
    	
        $.ajaxFileUpload({  
            url : "pic!updFile.do",  
            secureuri : false,// 一般设置为false  
            fileElementId : "file",// 文件上传表单的id <input type="file" id="fileUpload" name="file" />  
            dataType : 'json',// 返回值类型 一般设置为json  
            data: {'name': name,'filedir': '${filedir}','width':${width},'height':${height}},  
            success : function(data) // 服务器成功响应处理函数  
            {
            	var re = eval("(" + data + ")");
            	var timestamp=new Date().getTime();//id
            	if(re.status == 'success'){
            		var html = '<div class="divKJ"><div style="height: 120px"><img class="divIMG" src="${ctx}/public/images/upload/${filedir}/'+name+'.png?rand=${random}"></div><div style=" 110px;float: left;height:30px " ><input id="kd'
        			+timestamp+'" onblur="edit(this,\''+name+'.png\')"'+' type="text" value="'+name+'" style=" 150px;border:solid 0px #cc66cc;height:30px;background-color:#e1e1e1;color:black;" disabled="disabled"/></div>'
        			+'<div  style=" 40px;float: right;height:30px;margin-top: 6px">'
        			+'<img title="'+basicModule_zhct.resourceBundle.Text.edit+'" src="${ctx}/public/extjs/resources/icons/fam/editl.png" onclick="toInput(\'kd'+timestamp+'\')" style="cursor:pointer;"/>'
        			+'<img title="'+basicModule_zhct.resourceBundle.Text.del+'" src="${ctx}/public/extjs/resources/icons/fam/dell.png" onclick="del(\''+name+'.png\',this)" style="cursor:pointer;"/></div></div>'
        
            		$("#imgs").append(html);
            	}else{
            		Wg.alert(re.message);
            	}   
            },  
            error : function(data)// 服务器响应失败处理函数  
            {  
            	Wg.alert(basicModule_zhct.resourceBundle.Error.upload);
            }  
        });  
        return false;  
    }
    
    //获取图片名称  
    function getFileName(o){
        var pos=o.lastIndexOf("\\");
        var fileName = o.substring(pos+1);
        pos=fileName.lastIndexOf(".");
        return fileName.substring(0,pos);  
    }
    
    function del(name,tar){
    	Wg.confirm(basicModule_zhct.resourceBundle.Confirm.del, function() {
    		$.ajax({
    			type: 'POST',
    			url: 'pic!delFile.do', 
    	        data: {'name': name,'filedir': '${filedir}'},  
    	        success : function(data) // 服务器成功响应处理函数  
    	        {
    	        	var re = eval("(" + data + ")");
    	        	if(re.status == 'success'){
    	        		$(tar).parent().parent().remove();
    	        	}else{
    	        		Wg.alert(re.message);
    	        	}   
    	        },  
    	        error : function(data)// 服务器响应失败处理函数  
    	        {  
    	        	Wg.alert(basicModule_zhct.resourceBundle.Error.del);
    	        } 
    		});
    	});
    }
    function toInput(id){
    	if($("#"+id).attr("disabled")=="disabled"){	
    		$("#"+id).css('background-color','#FFFFFF');
    		$("#"+id).attr("disabled",false);
    		$("#"+id).focus();
    	}
    }
    function edit(tar,name){
    	var newName = $(tar).val();
    	//中文判断
    	var reg = /[\u4e00-\u9fa5]/g;
    	if(reg.test(newName)){
    		Wg.alert(basicModule_zhct.resourceBundle.Error.ischar);
    		console.log(newName.length);
    		$(tar).val(name.substring(0,name.length-4));
    		return false;
    	}
    	$(tar).attr("disabled",true);
    	$(tar).css('background-color','#e1e1e1');
    	
    	//修改
    	$.ajax({
    		type: 'POST',
    		url: 'pic!editFile.do', 
            data: {'name': name,'newName':newName,'filedir': '${filedir}'},  
            success : function(data) // 服务器成功响应处理函数  
            {
            	var re = eval("(" + data + ")");
            	if(re.status != 'success'){
            		Wg.alert(re.message);
            	}   
            },  
            error : function(data)// 服务器响应失败处理函数  
            {  
            	Wg.alert(basicModule_zhct.resourceBundle.Error.upload);
            } 
    	});
    }
    
    </script>
    <style>
    .fileInput{ 150px;height: 150px;overflow: hidden;opacity: 0;filter:alpha(opacity=0);cursor:pointer;}
    .divKJ{border: 1px solid #e1e1e1; 150px;height: 150px;float: left;margin-left: 30px;margin-top: 30px}
    .divIMG{150px;height: 120px}
    </style>
    </head>
    
    <body>
    	<div id="imgs">
    		<c:forEach items="${fienames}" var="item" varStatus="s">
    		<div class="divKJ">
    			<div style="height: 120px"><img class="divIMG" src="${ctx}/public/images/upload/${filedir}/${item}?rand=${random}"></div>
    			<div style=" 110px;float: left;height:30px;" >
    				<input id="kd${s.index}" onblur="edit(this,'${item}')" type="text" value='${fn:substringBefore(item, ".")}' style=" 150px;border:solid 0px #cc66cc;height:30px;background-color:#e1e1e1;color:black;margin:0" disabled="disabled"/>				
    			</div>
    			<div  style=" 40px;float: right;height:30px;margin-top: 6px">
    				 <img title="<s:text name="basicModule.dagl.zdda.edit" />" src="${ctx}/public/extjs/resources/icons/fam/editl.png" onclick="toInput('kd${s.index}')" style="cursor:pointer;"/>
    				 <img title="<s:text name="basicModule.dagl.zdda.del" />" src="${ctx}/public/extjs/resources/icons/fam/dell.png" onclick="del('${item}',this)" style="cursor:pointer;"/>
    			</div>
    		</div>
    		</c:forEach>
    	</div>
    	<div class="divKJ" style="border:solid 0px #cc66cc;margin-top:15px">
    		<input class="fileInput"  type="file" accept="image/*"  name="file" id="file" onchange ="uploadFile(this)"/> 
    		<img id="bg" src="${ctx}/public/images/upd.png" height="140px" width="140px;" style="margin-top:-150px;margin-left:13px"/>
    	</div>
    </body>
    </html>
    
  • 相关阅读:
    提取 Microsoft.ReportViewer.ProcessingObjectModel.dll Microsoft.ReportViewer.DataVisualization.dll 等dll(转贴)
    Windows API 逐个逐个学(0) MessageBox
    asp程序员使用asp.net中服务器控件的困惑
    SQLServer 存储过程中不拼接SQL字符串实现多条件查询
    工作学习笔记
    c#3.0/3.5 中的一些新特性
    firefox中使用ctrl+0解决了一个调试很长时间的问题
    使用Nunit进行单元测试
    asp.net 用户控件和自定义控件总结
    Visual Studio 2008 无法启动调试.找不到Microsoft Internet Explorer
  • 原文地址:https://www.cnblogs.com/xumin/p/2760794.html
Copyright © 2011-2022 走看看