用Servlvet实现文件上传的功能

该博客展示了一个Java文件上传模块,此模块无法处理嵌套数据和国际化内容。给出了文件上传示例,可自定义文件大小,当前为5M,FTP服务器目标路径为 /usr/local/jakarta - tomcat/bin。详细介绍了文件上传的实现过程,包括请求处理、文件大小检查、目录创建等。

// file upload module
// It cannot handle nested data (multipart content withinmultipart content)
// or internationalized content (such as non Latin-1 filenames).

//
// Designed by Mouse King, Last modified on August 2nd,2000
// file upload example
// one file control can upload a file once
// you can customize the file size,now it is 5m
// the ftp server target path is /usr/local/jakarta-tomcat/bin。

package BBS;

import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class UploadTest extends HttpServlet {
String rootPath, successMessage;

static final int MAX_SIZE = 102400;
public void init(ServletConfig config) throws ServletException
{
super.init(config);
}

public void doGet(HttpServletRequest request,HttpServletResponse response)
      throws ServletException,IOException
{
  response.setContentType("text/html");
  PrintWriter out = new PrintWriter (response.getOutputStream());
  out.println("<html>");
  out.println("<head><title>Servlet1</title></head>");
  out.println("<body><form ENCTYPE=/"multipart/form-data/" method=post action=''><input type=file enctype=/"multipart/form-data/" name=filedata>");
  out.println("<input type=submit></form>");
  out.println("</body></html>");
  out.close();
}


public void doPost(HttpServletRequest request,HttpServletResponse response)
{
  ServletOutputStream out=null;
  DataInputStream in=null;
  FileOutputStream fileOut=null;
  try
  {
  /*set content type of response and get handle to output stream in case we are unable to redirect client*/
    response.setContentType("text/plain");
    out = response.getOutputStream();
  }
  catch (IOException e)
  {
    //print error message to standard out
    System.out.println("Error getting output stream.");
    System.out.println("Error description: " + e);
    return;
  }

  try
  {
  String contentType = request.getContentType();
  //make sure content type is multipart/form-data
  if(contentType != null && contentType.indexOf("multipart/form-data") != -1)
  {
    //open input stream from client to capture upload file
    in = new DataInputStream(request.getInputStream());
    //get length of content data
    int formDataLength = request.getContentLength();
    //allocate a byte array to store content data
    byte dataBytes[] = new byte[formDataLength];
    //read file into byte array
    int bytesRead = 0;
    int totalBytesRead = 0;
    int sizeCheck = 0;
    while (totalBytesRead < formDataLength)
    {
      //check for maximum file size violation
      sizeCheck = totalBytesRead + in.available();
      if (sizeCheck > MAX_SIZE)
      {
        out.println("Sorry, file is too large to upload.");
        return;
      }
      bytesRead = in.read(dataBytes, totalBytesRead, formDataLength);
      totalBytesRead += bytesRead;
    }
    //create string from byte array for easy manipulation
    String file = new String(dataBytes);
    //since byte array is stored in string, release memory
    dataBytes = null;
    /*get boundary value (boundary is a unique string that
    separates content data)*/
    int lastIndex = contentType.lastIndexOf("=");
    String boundary = contentType.substring(lastIndex+1,
    contentType.length());
    //get Directory web variable from request
    String directory="";
    if (file.indexOf("name=/"Directory/"") > 0)
    {
      directory = file.substring(file.indexOf("name=/"Directory/""));
      //remove carriage return
      directory = directory.substring(directory.indexOf("/n")+1);
      //remove carriage return
      directory = directory.substring(directory.indexOf("/n")+1);
      //get Directory
      directory = directory.substring(0,directory.indexOf("/n")-1);
      /*make sure user didn't select a directory higher in the directory tree*/
      if (directory.indexOf("..") > 0)
      {
        out.println("Security Error: You can't upload " +"to a directory higher in the directory tree.");
        return;
      }
    }
  //get SuccessPage web variable from request
  String successPage="";
  if (file.indexOf("name=/"SuccessPage/"") > 0)
  {
  successPage = file.substring(file.indexOf("name=/"SuccessPage/""));
  //remove carriage return
  successPage = successPage.substring(successPage.indexOf("/n")+1);
  //remove carriage return
  successPage = successPage.substring(successPage.indexOf("/n")+1);
  //get success page
  successPage = successPage.substring(0,successPage.indexOf("/n")-1);}
  //get OverWrite flag web variable from request
  String overWrite;
  if (file.indexOf("name=/"OverWrite/"") > 0)
  {
  overWrite = file.substring(file.indexOf("name=/"OverWrite/""));
  //remove carriage return
  overWrite = overWrite.substring(
  overWrite.indexOf("/n")+1);
  //remove carriage return
  overWrite = overWrite.substring(overWrite.indexOf("/n")+1);
  overWrite = overWrite.substring(0,overWrite.indexOf("/n")-1);
  }
  else
  {
  overWrite = "false";
  }
  //get OverWritePage web variable from request
  String overWritePage="";
  if (file.indexOf("name=/"OverWritePage/"") > 0)
  {
  overWritePage = file.substring(file.indexOf("name=/"OverWritePage/""));
  //remove carriage return
  overWritePage = overWritePage.substring(overWritePage.indexOf("/n")+1);
  //remove carriage return
  overWritePage = overWritePage.substring(overWritePage.indexOf("/n")+1);
  //get overwrite page
  overWritePage = overWritePage.substring(0,overWritePage.indexOf("/n")-1);
  }
  //get filename of upload file
  String saveFile = file.substring(file.indexOf("filename=/"")+10);
  saveFile = saveFile.substring(0,saveFile.indexOf("/n"));
  saveFile = saveFile.substring(saveFile.lastIndexOf("//")+1,
  saveFile.indexOf("/""));
  /*remove boundary markers and other multipart/form-data
  tags from beginning of upload file section*/
  int pos; //position in upload file
  //find position of upload file section of request
  pos = file.indexOf("filename=/"");
  //find position of content-disposition line
  pos = file.indexOf("/n",pos)+1;
  //find position of content-type line
  pos = file.indexOf("/n",pos)+1;
  //find position of blank line
  pos = file.indexOf("/n",pos)+1;
  /*find the location of the next boundary marker
  (marking the end of the upload file data)*/
  int boundaryLocation = file.indexOf(boundary,pos)-4;
  //upload file lies between pos and boundaryLocation
  file = file.substring(pos,boundaryLocation);
  //build the full path of the upload file
  String fileName = new String(rootPath + directory +
  saveFile);
  //create File object to check for existence of file
  File checkFile = new File(fileName);
  if (checkFile.exists())
  {
  /*file exists, if OverWrite flag is off, give
  message and abort*/
  if (!overWrite.toLowerCase().equals("true"))
  {
  if (overWritePage.equals(""))
  {
  /*OverWrite HTML page URL not received, respond
  with generic message*/
  out.println("Sorry, file already exists.");
  }
  else
  {
  //redirect client to OverWrite HTML page
  response.sendRedirect(overWritePage);
  }
  return;
  }
  }
  /*create File object to check for existence of
  Directory*/
  File fileDir = new File(rootPath + directory);
  if (!fileDir.exists())
  {
  //Directory doesn't exist, create it
  fileDir.mkdirs();
  }
  //instantiate file output stream
  fileOut = new FileOutputStream(fileName);
  //write the string to the file as a byte array
  fileOut.write(file.getBytes(),0,file.length());
  if (successPage.equals(""))
  {
  /*success HTML page URL not received, respond with
  eneric success message*/
  out.println(successMessage);
  out.println("File written to: " + fileName);
  }
  else
  {
  //redirect client to success HTML page
  response.sendRedirect(successPage);
  }
  }
  else //request is not multipart/form-data
  {
  //send error message to client
  out.println("Request not multipart/form-data.");
  }
  }
  catch(Exception e)
  {
  try
  {
  //print error message to standard out
  System.out.println("Error in doPost: " + e);
  //send error message to client
  out.println("An unexpected error has occurred.");
  out.println("Error description: " + e);
  }
  catch (Exception f) {}
  }
  finally
  {
  try
  {
  fileOut.close(); //close file output stream
  }
  catch (Exception f) {}
  try
  {
  in.close(); //close input stream from client
  }
  catch (Exception f) {}
  try
  {
  out.close(); //close output stream to client
  }
  catch (Exception f) {}
  }
  }

}

代码转载自:https://pan.quark.cn/s/8ce4326d996e 对于在 CentOS 7 系统中修改网卡配置文件后无法使设置生效的情况,经过实践验证,可以通过使用 nmcli 命令来进行调整。完成修改之后,需要重新启动虚拟机以使更改生效,这样操作流程即告完成。如果设置仍然无法生效,则表明虚拟机在启动过程中所获取的 IP 地址配置并非针对 eth0,此时可以对其它网卡的配置文件进行修改或将其移除。在 CentOS 7 系统中,网络配置的管理机制与早期版本存在差异,主要体现为采用了 Network Manager 服务来负责网络接口的管理。在某些情形下,尽管修改了 `/etc/sysconfig/network-scripts` 目录下的 `ifcfg-eth0` 文件,但网络配置却未能即时生效。此类问题的发生通常源于 CentOS 7 采用了不同于以往的配置读取方法。接下来将具体阐述如何借助 nmcli 命令来处理这一挑战。 以 root 用户身份登录系统并打开终端界面。nmcli 是 Network Manager 提供的命令行界面工具,它支持在命令行环境下执行网络连接的建立、编辑、查询及管理任务。针对修改 eth0 网卡配置的需求,可以遵循以下步骤进行操作: 1. 导航至 `/etc/sysconfig/network-scripts` 目录: ``` cd /etc/sysconfig/network-scripts ``` 2. 检查该目录内是否存在 `ifcfg-eth0.bak` 文件,该备份文件可能是先前调整配置时遗留下来的,若存在可能造成冲突。若发现该文件,可以选择将其删除: ``` [root@localhost netw...
代码转载自:https://pan.quark.cn/s/46fd08fb879c 网管教程 从入门到精通软件篇 ★一。★详尽的xp修复控制台指令及其应用!!! 放入xp(2000)的光盘,安装时选择R,执行修复! Windows XP(涵盖 Windows 2000)的控制台指令是在系统遭遇某些意外状况时的一种极具效用的诊断、检测以及恢复系统功能的工具。笔者确实一直期望能够将这方面的指令进行归纳,此次由老范辛苦整理了这份极具价值的秘籍。 Bootcfg bootcfg 命令用于启动配置与故障恢复(对大多数计算机而言,即 boot.ini 文件)。 带有特定参数的 bootcfg 命令仅在运用故障恢复控制台时方可使用。能够在命令行界面下运用带有不同参数的 bootcfg 命令。 用法: bootcfg /default 设定默认引导选项。 bootcfg /add 向引导清单中增添 Windows 安装。 bootcfg /rebuild 重复整个 Windows 安装流程并让用户选择需添加的项目。 注意:运用 bootcfg /rebuild 之前,应先借助 bootcfg /copy 命令备份 boot.ini 文件。 bootcfg /scan 探查用于 Windows 安装的全部磁盘并展示结果。 注意:这些结果被静态存储,并用于当前会话。若在当前会话期间磁盘配置发生变动,为获取更新的探查结果,必须先重启计算机,然后再次探查磁盘。 bootcfg /list 列示引导清单中已有的项目。 bootcfg /disableredirect 在启动引导程序中禁用重定向。 bootcfg /redirect [ PortBaudRrate] |[ useBio...
代码下载链接: https://pan.quark.cn/s/fc524f791b68 AA制程,即Active Alignment,被理解为主动对准,是一种用于确定零部件装配中相对位置的方法。在摄像头封装阶段,涉及图像传感器、镜座、马达、镜头、线路板等多个部件的重复组装,而传统的封装设备如CSP及COB等,均是依据设备设定的参数进行零部件的移动装配,因而零部件的叠加误差会逐渐增大,最终在摄像头上表现为拍照最清晰的位置可能偏离画面中心、四边清晰度不均等现象。伴随智能手机和其他高端电子产品的普及,摄像头模组的性能正日益受到重视。高分辨率、卓越的低光表现以及稳定视频输出是现代用户所期望的。在摄像头模组的制造环节,各部件的精准定位对成像质量具有决定性作用。因此,一种名为“AA制程”(Active Alignment)的前沿技术被开发出来,成为摄像头精密对准的核心技术。 AA制程,即Active Alignment,是一种在摄像头封装过程中应用的主动对准方法。该方法在多个组件装配阶段发挥作用,涵盖图像传感器、镜座、马达、镜头和线路板等部件。传统的封装方式,例如CSP(Chip Scale Package)和COB(Chip On Board),依赖于设备预设的参数进行组装,但随着组件数量的增加,误差也会累积,最终影响摄像头的表现。例如在成像质量上可能出现中心位置偏移、四角清晰度不一致等问题。 AA制程技术的核心在于实时监测与主动调整。在组装过程中,它借助先进的检测设备持续监控半成品的状态,并根据实时信息对组装部件进行精确修正,从而显著降低装配误差。通过这种技术,能够确保摄像头模组中各组件的相对位置准确无误,从而使得最终的成像效果更加稳定,特别是在中心区域和四角的清晰度上...
内容概要:本文介绍了一套基于Matlab实现的光子晶体90度弯曲波导的二维时域有限差分法(2D FDTD)仿真代码,旨在通过数值模拟手段深入研究光子晶体波导中的光传播特性。该资源聚焦于电磁场与光子学领域的仿真技术应用,系统实现了FDTD算法在复杂介质结构中的建模过程,涵盖空间网格剖分、时间步进迭代、完美匹配层(UPML)边界条件处理、总场散射场(TFSF)激励源设置、介电常数分布定义及电磁场演化可视化等核心模块,能够有效分析光在90度弯曲波导中的传输效率、模式分布与反射损耗等关键性能指标。; 适合人群:具备电磁场理论基础和Matlab编程能力的研究生、科研人员以及从事光子晶体器件设计与仿真的工程技术人员。; 使用场景及目标:①用于教学演示FDTD方法的基本原理与算法流程,帮助理解麦克斯韦方程的离散化求解过程;②支撑科研工作中对光子晶体弯曲波导结构的传输特性进行仿真分析与性能优化;③作为开发更复杂光子集成器件(如分束器、滤波器)数值仿真工具的基础框架; 阅读建议:建议使用者结合经典FDTD教材(如Taflove著作)深入理解算法理论,并在Matlab环境中逐模块调试代码,重点关注电场与磁场的交替更新过程、UPML吸收边界的设计实现以及TFSF源的引入方式,从而全面提升对时域电磁仿真机制的掌握与应用能力。
内容概要:本文围绕直驱式永磁同步电机(PMSM)的矢量控制仿真模型展开研究,基于Simulink平台构建了完整的电机控制系统仿真模型,涵盖电机本体建模、坐标变换(如Clark变换与Park变换)、磁场定向控制(FOC)、电流环与速度环的PI调节、空间矢量脉宽调制(SVPWM)等核心技术环节,旨在实现对电机转矩与转速的高精度、动态响应良好的控制。通过系统化仿真验证控制策略的有效性与鲁棒性,深入分析各模块间的信号流向与控制逻辑,为电机驱动系统的设计与优化提供理论依据和技术支撑,是理论联系工程实践的重要桥梁。; 适合人群:具备电机学、电力电子与自动控制基础知识,熟悉Simulink/MATLAB仿真环境,从事电气工程、自动化、新能源车辆、智能制造等方向的研究生、科研人员及工程技术人员。; 使用场景及目标:①深入理解永磁同步电机矢量控制的核心原理与系统架构;②掌握在Simulink中从零开始搭建复杂电机控制系统的方法与技巧;③应用于课程设计、毕业论文、科研项目中的控制算法验证、参数整定与性能优化;④为后续的硬件在环(HIL)测试或实物系统开发奠定仿真基础。; 阅读建议:建议结合经典电机控制理论教材同步学习,注重理论推导与仿真实现的对应关系,动手实践模型搭建、参数调试与波形分析,特别关注PI控制器参数整定对系统稳定性、动态响应速度和抗干扰能力的影响,通过反复仿真迭代加深对控制机理的理解。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值