文件上传

package com.fileupload;

import java.io.*;
import java.sql.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import org.apache.commons.fileupload.*;

import sun.rmi.server.Dispatcher;

public class FileUpLoad extends HttpServlet {
	String result="花木成畦手自栽";
	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * The doPost method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to
	 * post.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	/*
	 * 将文件上传到服务器中并保存在硬盘中start public void doPost(HttpServletRequest request,
	 * HttpServletResponse response) throws ServletException, IOException {
	 * 
	 * response.setContentType("text/html;charset=uft-8");
	 * request.setCharacterEncoding("utf-8");
	 * response.setCharacterEncoding("utf-8"); PrintWriter out =
	 * response.getWriter();
	 * 
	 * //设置上传文件的保存目录 , String
	 * uploadDir=getServletContext().getRealPath("/uploadfile");
	 * if(uploadDir==null){ out.println("无法访问存储目录!"); return; } // File
	 * fileupload=new File(uploadDir); if(!fileupload.exists()){
	 * //不存在则在当前应用下创建这个文件夹 if(!fileupload.mkdir()){ out.print("无法创建该目录!");
	 * return; } } DiskFileUpload dsfileup=new DiskFileUpload();
	 * //设置上传的普通字段的名称和文件字段的文件名所采用的字符集编码
	 * dsfileup.setHeaderEncoding(request.getCharacterEncoding()); //设置上传文件的最大值
	 * dsfileup.setSizeMax(1024*1024*200);
	 * 
	 * //得到所有表单字段对象的集合 List fileItems=null; try {
	 * fileItems=dsfileup.parseRequest(request); } catch (FileUploadException e) { //
	 * TODO Auto-generated catch block out.print("解析数据时出现以下异常!");
	 * e.printStackTrace(out); } //处理每个表单的数据 Iterator item=fileItems.iterator();
	 * while(item.hasNext()){ FileItem fi=(FileItem)item.next();
	 * if(fi.isFormField()){ out.print("表单名:"+fi.getFieldName()+"<br>表单值:"+fi.getString("utf-8")+"<br>");
	 * }else{ if(fi.getFieldName()!=null&&!fi.getName().equals("")){ out.print("<br>上传文件的大小为:"+fi.getSize()+"KB");
	 * out.print("<br>上传文件的类型为:"+fi.getContentType()); out.print("<br>上传文件的名称为:"+fi.getName());
	 * File tempfile=new File(fi.getName()); File file=new
	 * File(uploadDir,tempfile.getName()); try { fi.write(file); out.print("<br>上传文件成功!<br>"); }
	 * catch (Exception e) { // TODO Auto-generated catch block
	 * e.printStackTrace(); out.print("<br>上传文件失败"); }
	 * 
	 * }else{ out.print("<br>请选择上传文件!"); } } } } 将文件上传到服务器中并保存在硬盘中stop
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		response.setCharacterEncoding("utf-8");
		request.setCharacterEncoding("utf-8");
		DiskFileUpload upload = new DiskFileUpload();
		// 设置转换时的编码
		upload.setHeaderEncoding(request.getAuthType());
		// 设置上传文件的最大值为100M
		upload.setSizeMax(1024 * 1024 * 100);
		// 设置上专文件时使用临时文件的临届值
		upload.setSizeThreshold(1024 * 1024 * 20);
		List fileItems = null;
		// 如果是多媒体格式则用List集合保存所有的字段元素值
		if (upload.isMultipartContent(request)) {
			try {
				fileItems = upload.parseRequest(request);
			} catch (FileUploadException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		// 迭代List集合,并将所有表单元素的值与名字放入到Map集合中
		HashMap map = new HashMap();
		Iterator item = fileItems.iterator();
		// 循环得到FileItem对象
		while (item.hasNext()) {
			FileItem fi = (FileItem) item.next();
			// 如果是普通表单,将表单名与值放入到map集合中
			if (fi.isFormField()) {
				map.put(fi.getName(), fi.getString());
			} else {
				// 如果是多媒体数据,则将对象名与对象放到map集合中
				map.put(fi.getFieldName(), fi);
			}
		}
		// 并将文件写入到数据 库中
		save((FileItem) map.get("fileUpLoad"));
		// System.out.print("对象是"+(FileItem)map.get("fileUpLoad"));
		//将上传的结果放到request对象中。
		request.setAttribute(result,result);
		//构建临时文件。用来取得上传文件的文件名。
		File tempfile = new File(((FileItem)map.get("fileUpLoad")).getName());
		//转交到显存图片的servlet进行处理
		RequestDispatcher rd=request.getRequestDispatcher("showImage.jsp?filename="+tempfile.getName());
		rd.forward(request, response);
	}

	public void save(FileItem fileitem) {
		// 创建一个临时文件。用来得到上传文件中不带路径的文件名
		File tempfile = new File(fileitem.getName());
		// String filename=tempfile.getName();
		// System.out.print(filename);
		Connection con = null;
		try {
			// 调用DBHelper类的getgetInstance方法得到一个类的实例。并调用实例方法getConnection得到一个连接
			con = DBHelper.getgetInstance().getConnection();
			String sql = "insert into bookImage ([filename],image)values(?,?) ";
			// 创建一个PreparedStatement对象预编译SQL语句
			PreparedStatement ps = con.prepareStatement(sql);

			// 把FileItem对象的主体内容转换成输入流
			InputStream is = fileitem.getInputStream();
			// 为SQL语句传参数值
			ps.setString(1, tempfile.getName());
			ps.setBinaryStream(2, is, (int) fileitem.getSize());
			// 执行编译好的SQL语句
			int num = ps.executeUpdate();
			if (1 != num){
				System.err.println("上傳失敗");
				result="上傳失敗";
			}else{
			ps.close();
			is.close();
			System.out.println("上傳成功");
			result="上傳成功";
			}
		} catch (Exception e) {
			System.out.print(e.getMessage());
		}finally{
			try {
				// close the connection
				if (con != null)
					con.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * Initialization of the servlet. <br>
	 * 
	 * @throws ServletException
	 *             if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

}

 

  • 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的并行计算工具箱加速计算过程,特别是当样本量很大时。 #### 五、应用场景 该程序适用于需要进行非线性回归预测的场景,如经济预测、天气预报等领域。通过调整核函数和参数,可以有效应对各种类型的非线性问题。 ### 总结 本程序提供了一个支持向量机非线性回归的完整实现框架,通过灵活的核函数设置和参数调整,能够有效地处理非线性问题。对于需要进行回归预测的应用场景,这是一个非常实用且强大的工具。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值