简单 文件上传

index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>文件上传页面测试</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
  </head>
  
  <body>
   	<form action="servlet/UpLoad" method="post" enctype="multipart/form-data">
   		<input type="file" name="uploadfile">
   		<input type="submit" name="submit" value="上传">
   	</form>
  </body>
</html>

 

showpic.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="java.sql.*,javax.sql.*,javax.naming.*,java.io.*"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>显示数据库中的图片对象</title>
</head>
<body>
	上传用户名:${requestScope.username }<br>
	<img src="ShowImage?picid=23" width="500px" height="600px">
		<!-- 读取查询数据库中的图片对象 -->
	<%--
		Context context=new InitialContext();
		DataSource ds=(DataSource)context.lookup("java:/comp/env/jdbc/upload");
		Connection con=ds.getConnection();
		String sql="select pic_image from pic where pic_id=23";
		PreparedStatement preparedStatement= con.prepareStatement(sql);
		ResultSet rs=preparedStatement.executeQuery();    //得到查询结果集
		Blob picture=null;
		if(rs.next()){
			picture=rs.getBlob(1);
			long size=picture.length();    //得到图片长度
			byte [] bs=picture.getBytes(1,(int)size);
			OutputStream os=response.getOutputStream();
			os.write(bs);    //指定byte数组写入输出流
			os.flush();    //刷新输出流,写出缓冲的输出字节
   
            out.clear();    //JspWriter
            out = pageContext.pushBody();  //BodyContent is a subclass of JspWriter 返回一个空的out对象
           
            //public BodyContent pushBody()
            //Return a new BodyContent object, save the current "out" JspWriter, 
            //and update the value of the "out" attribute in the page scope attribute namespace of the PageContext
            
            //public abstract void clear()throws IOException
            //Clear the contents of the buffer. 
            //If the buffer has been already been flushed 
            //then the clear operation shall throw an IOException to signal the fact that 
            //some data has already been irrevocably written to the client response stream
		}else{
			out.println("没有找到图片");
		}
		
	 --%>
	 
</body>
</html>

 

 

 

 

 uploadDatabase.jsp

<%@ page language="java" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>文件上传例题</title>
<style type="text/css">
	form{ margin-top:100px;}
</style>
</head>

<body>
  目录1:<%=request.getSession().getServletContext().getContextPath()%>
  目录2:<%=request.getSession().getServletContext().getRealPath("/")%>
<form action="servlet/UpLoadDatabase" method="post" enctype="multipart/form-data" name="form1" id="form1">
  <table width="580" border="0" align="center" cellpadding="10" cellspacing="1" bgcolor="#999999">
    <tr>
      <td bgcolor="#FFFFFF">网名:</td>
      <td colspan="2" bgcolor="#FFFFFF"><input name="username" type="text" id="username" /></td>
    </tr>
    <tr>
      <td bgcolor="#FFFFFF">文件:</td>
      <td colspan="2" bgcolor="#FFFFFF"><input type="file" name="file" /></td>
    </tr>
    <tr>
      <td bgcolor="#FFFFFF">&nbsp;</td>
      <td bgcolor="#FFFFFF"><input name="submit" type="submit" id="submit" value="提交" /></td>
      <td bgcolor="#FFFFFF"><input name="reset" type="reset" id="reset" value="刷新" /></td>
    </tr>
  </table>
</form>
</body>
</html>

 

 

 

 

 

 

 

package servlets;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;

import javax.naming.*;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.*;
import javax.imageio.*;

public class ShowImage extends HttpServlet {

	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		System.out.println("图片查un:"+request.getParameter("picid"));
		//从客户端获取要查询的ID
		Integer picid=new Integer(request.getParameter("picid"));
		System.out.println("图片的ID"+picid);
		//数据库连接对象,方便finally使用
		Connection con=null;
		
		//预处理命令对象
		PreparedStatement ps=null;
		
		//结果集对象
		ResultSet rs=null;
		try{
			Context context=new InitialContext();
			DataSource ds=(DataSource)context.lookup("java:comp/env/jdbc/upload");
			
			//得到数据库连接对象
			con=ds.getConnection(); 
			String sql="select pic_image from pic where pic_id=?";
			ps=con.prepareStatement(sql);
			
			//设置查询参数
			ps.setInt(1,picid);
			
			//执行查询
			rs=ps.executeQuery();
			if(rs.next()){
				response.setContentType("image/png");
				Blob pic=rs.getBlob(1);
				System.out.println(pic);
				//得到向客户端响应的输出流
				ServletOutputStream sos=response.getOutputStream();
				
				//通过二进制大对象得到输入流
				InputStream is=pic.getBinaryStream();
				
				//通过ImageIO的静态方法得到BufferedImage
				BufferedImage image=ImageIO.read(is);
				System.out.println("图片"+pic);
				/*
				 * 使用指定的png格式把(实现RenderedImage接口的BufferedImage)
				 * image对象写入OutputStream 类型对象
				 */
				ImageIO.write(image,"png",sos);
				
				//关闭输入流对象
				is.close();
				
				//刷新输出流,写出缓冲的输出字节
				sos.flush();
				sos.close();
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			try {
				if(con!=null){
					con.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}//关闭数据库连接try块
		}
	}

	public void init() throws ServletException {
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request,response);
	}

}

 

 

 

 

 

 

 

package servlets;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.*;

public class UpLoad extends HttpServlet {

	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try{
		DiskFileUpload fu=new DiskFileUpload();
		PrintWriter out=response.getWriter();
		
		//设置上传对象的字符编码和request一致
		fu.setHeaderEncoding(request.getCharacterEncoding());
		
		//限制上传文件大小
		fu.setSizeMax(1024*1024*16);
		
		//设置临时保存解析占用内存空间大小
		fu.setSizeThreshold(1024*1024*16);
		List fileItems=fu.parseRequest(request);
		Iterator it=fileItems.iterator();
		FileItem fi=(FileItem)it.next();  //解析成fileItem
		String name=fi.getName();    //得到文件路径和名字
		
		if(name.lastIndexOf("\\")!=-1){
			//得到文件名去除路径名
			String filename=name.substring(name.lastIndexOf("\\"));
			String webdir=request.getSession().getServletContext().getRealPath("/");
			fi.write(new File(webdir+"uploadimage"+filename));
			
			out.print("上传成功");
		}else{
			out.print("上传失败!");
		}	
		}catch(Exception e){
			e.printStackTrace();
		}
	}

	public void init() throws ServletException {
		
	}

}

 

 

 

 

 

/**
 * 上传信息到数据库包括图片
 */
package servlets;

import java.io.*;
import java.util.*;
import java.sql.*;

import javax.naming.*;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.*;

import org.apache.commons.fileupload.*;

/**
 *
 *
 */
public class UpLoadDatabase extends HttpServlet {
	private static final long serialVersionUID = 5220553409822159109L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request,response);
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		DiskFileUpload df=new DiskFileUpload();
		df.setHeaderEncoding(request.getCharacterEncoding());
		df.setSizeMax(1024*1024*16);    //设置文件最大为16M
		df.setSizeThreshold(1024*1024*3);    //设置内存中缓冲3M
		if(df.isMultipartContent(request)){
			InputStream is=null;
			PreparedStatement pst=null;
			Connection con=null;
			try {
				Map map=new HashMap();
				List fileList=df.parseRequest(request);    //解析请求到list集合
				Iterator fileItems=fileList.iterator();    //迭代器
				while(fileItems.hasNext()){
					FileItem ft=(FileItem)fileItems.next();
					if(ft.isFormField()){    //如果不是文件
						map.put(ft.getFieldName(),ft.getString());
						request.setAttribute(ft.getFieldName(),ft.getString());
					}else{
						map.put(ft.getFieldName(),ft);
					}					
				}//遍历迭代器对象循环
				FileItem file=(FileItem)map.get("file");
				Context context = new InitialContext();
				DataSource ds = (DataSource) context.lookup("java:comp/env/jdbc/upload");
				con = ds.getConnection();
				String inserta = "insert into pic (pic_name,pic_image) values (?,?)";
				pst = con.prepareStatement(inserta);
				pst.setString(1, map.get("username").toString());
				is = file.getInputStream(); //得到文件输入流
				pst.setBinaryStream(2, is, (int)file.getSize());
				int result = pst.executeUpdate(); //执行更新插入数据
				if (result >= 1) {
					request.setAttribute("result", "上传文件成功!");
				} else {
					request.setAttribute("result", "上传文件失败!");
				}//判断是否上传成功块结束
			} catch (Exception e) {
				System.out.println(new String(e.getMessage().getBytes("ISO-8859-1"),"GBK"));
				e.printStackTrace();
			}finally{
				try {
					pst.close();
					con.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}    
		}else{
			request.setAttribute("result","只能处理multipart/form-data类型的数据!");
			return;
		}//判断是否是multipart/form-data类型数据块结束
		//request.setAttribute("picid",23);
		System.out.println("目录1"+request.getSession().getServletContext().getContextPath());
		System.out.println("目录2"+request.getSession().getServletContext().getRealPath("/"));
		RequestDispatcher td=request.getRequestDispatcher("../showpic.jsp?picid=23");
		td.forward(request,response);
	}
}

 

 

相关源代码

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 支持向量机非线性回归通用MATLAB程序解析 #### 一、概述 本文将详细介绍一个基于MATLAB的支持向量机(SVM)非线性回归的通用程序。该程序采用支持向量机方法来实现数据的非线性回归,并通过不同的核函数设置来适应不同类型的数据分布。此外,该程序还提供了数据预处理的方法,使得用户能够更加方便地应用此程序解决实际问题。 #### 二、核心功能与原理 ##### 1. 支持向量机(SVM) 支持向量机是一种监督学习模型,主要用于分类和回归分析。对于非线性回归任务,SVM通过引入核技巧(kernel trick)将原始低维空间中的非线性问题转换为高维空间中的线性问题,从而实现有效的非线性建模。 ##### 2. 核函数 核函数的选择直接影响到模型的性能。本程序内置了三种常用的核函数: - **线性核函数**:`K(x, y) = x'y` - **多项式核函数**:`K(x, y) = (x'y + 1)^d` - **径向基函数(RBF)**:`K(x, y) = exp(-γ|x - y|^2)` 其中RBF核函数被广泛应用于非线性问题中,因为它可以处理非常复杂的非线性关系。本程序默认使用的是RBF核函数,参数`D`用于控制高斯核函数的宽度。 ##### 3. 数据预处理 虽然程序本身没有直接涉及数据预处理的过程,但在实际应用中,对数据进行适当的预处理是非常重要的。常见的预处理步骤包括归一化、缺失值处理等。 ##### 4. 模型参数 - **Epsilon**: ε-insensitive loss function的ε值,控制回归带宽。 - **C**: 松弛变量的惩罚系数,控制模型复杂度与过拟合的风险之间的平衡。 #### 三、程序实现细节 ##### 1. 函数输入与输出 - **输入**: - `X`: 输入特征矩阵,维度为(n, l),其中n是特征数量,l是样本数量。 - `Y`: 目标值向量,长度为l。 - `Epsilon`: 回归带宽。 - `C`: 松弛变量的惩罚系数。 - `D`: RBF核函数的参数。 - **输出**: - `Alpha1`: 正的拉格朗日乘子向量。 - `Alpha2`: 负的拉格朗日乘子向量。 - `Alpha`: 拉格朗日乘子向量。 - `Flag`: 标记向量,表示每个样本的类型。 - `B`: 偏置项。 ##### 2. 核心代码解析 程序首先计算所有样本间的核矩阵`K`,然后构建二次规划问题并求解得到拉格朗日乘子向量。根据拉格朗日乘子的值确定支持向量,并计算偏置项`B`。 - **核矩阵计算**:采用RBF核函数,通过`exp(-(sum((xi-xj).^2)/D))`计算任意两个样本之间的相似度。 - **二次规划**:构建目标函数和约束条件,使用`quadprog`函数求解最小化问题。 - **支持向量识别**:根据拉格朗日乘子的大小判断每个样本是否为支持向量,并据此计算偏置项`B`。 #### 四、程序扩展与优化 - **多核函数支持**:可以通过增加更多的核函数选项,提高程序的灵活性。 - **自动调参**:实现参数自动选择的功能,例如通过交叉验证选择最优的`Epsilon`和`C`值。 - **并行计算**:利用MATLAB的并行计算工具箱加速计算过程,特别是当样本量很大时。 #### 五、应用场景 该程序适用于需要进行非线性回归预测的场景,如经济预测、天气预报等领域。通过调整核函数和参数,可以有效应对各种类型的非线性问题。 ### 总结 本程序提供了一个支持向量机非线性回归的完整实现框架,通过灵活的核函数设置和参数调整,能够有效地处理非线性问题。对于需要进行回归预测的应用场景,这是一个非常实用且强大的工具。
项目:JavaScript 中的 Canyon Runner 游戏 Canyon Runner Game 是一个 HTML5 和 JavaScript 项目。这款游戏看起来很棒,玩起来很有趣。这款游戏使用了 Phaser框架。如果你想编写一个简单的游戏,那么这款射击游戏就是你必玩的游戏。这款游戏包含大量 JavaScript,用于对游戏的某些部分进行验证。 游戏玩法 要运行此游戏,您不需要任何类型的本地服务器,但需要 浏览器。您可以使用 Google Chrome 或 Mozilla Firefox 获得更好、更优化的游戏体验。要先玩游戏,请在浏览 器中单击 index.html 文件打开游戏。打开后,将出现一个带有开始菜单选项的屏幕。游戏的控制是箭头键和空格键,用于射击障碍物。游戏有一个主要的太空敌人和一个健康强化。具有惊人的视差效果、复古声音等。 这款游戏的射击是自动的。当你开始游戏时,射手开始发射火箭。记住这是一款两级或两章的游戏。第一级处理障碍和障碍。你需要越过这些障碍,不要让它们碰到你。即使它们碰到你,你也可以通过吃健康能量来恢复你的健康。你可以跑得更快,也可以控制你的宇宙飞船速度。 当你通过第一关后,你将在第二章中面对主要敌人。他会不断向你发射火箭导弹。你必须躲避它们并保护自己。你可以用火箭导弹攻击敌人来杀死他们。如果你能杀死敌人,你就赢了游戏。 这款游戏玩起来很有趣,重制它更是有趣。所以希望你能给这款游戏添加一些额外的关卡。 要查看我们的项目,您可以查看下面的图像滑块。我们建议您使用 Google Chrome 以获得更好的游戏性能。 演示: 该项目为国外大神项目,可以作为毕业设计的项目,也可以作为大作业项目,不用担心代码重复,设计重复等,如果需要对项目进行修改,需要具备一定基础知识。 注意:如果装有360等杀毒软件,可能会出现误报的情况,源码本身并无病毒,使用源码时可以关闭360,或者添加信任。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值