Upload file to servlet without using HTML form

Coding Plan:面向真实开发场景的能力交付系统 在软件工程实践中,‘编码能力’正从知识掌握转向可验证、可交付的工程信用。本文聚焦开发者能力成长的核心矛盾——学了不会用、用了不被认、认了难进阶,深入解析基于原子能力模型(如接口契约意识、错误防御密度)构建的实战化训练体系。结合国内‘需求黑洞+上线即事故’与海外‘可审计性+责任可追溯’双轨场景,系统阐述如何通过AST语义分析、Docker-in-Docker沙盒验证、Docs as Code证据链生成等关键技术,将代码编写升维为具备业务穿透力与协作可信度的工程行为。适用于转行新人、3年期中级开发者及技术团队T 阅读详情
It’s trivial to use a web form which is made by HTML code for uploading files from web browser to a server. This is commonly referred as form based file upload, and typically suitable for web-based applications. How about standalone or command line-based applications – which sometimes need to upload files to a web server but cannot use an upload form in HTML? Well, this article is going to answer that question by implementing the following solution:
    • Server: uses a Java servlet for receiving file uploaded from client and saves it into a file on server’s disk.
    • Client: is a command line based program that sends an HTTP POST request along with file’s binary data to the servlet.
We can call this method as non-form based file upload. Keep in mind that, this is not FTP upload, because it is still using HTTP protocol for transmitting the file. Let’s examine how each part is implemented.

Coding the servlet

Write a Java servlet as follows:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package net.codejava.servlet;
 
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
/**
  * This servlet demonstrates how to receive file uploaded from the client
  * without using third-party upload library such as Commons File Upload.
  * @author www.codejava.net
  */
public class ReceiveFileServlet extends HttpServlet {
     static final String SAVE_DIR = "E:/Test/Upload/" ;
     static final int BUFFER_SIZE = 4096 ;
     
     protected void doPost(HttpServletRequest request,
             HttpServletResponse response) throws ServletException, IOException {
         
         // Gets file name for HTTP header
         String fileName = request.getHeader( "fileName" );
         File saveFile = new File(SAVE_DIR + fileName);
         
         // prints out all header values
         System.out.println( "===== Begin headers =====" );
         Enumeration<String> names = request.getHeaderNames();
         while (names.hasMoreElements()) {
             String headerName = names.nextElement();
             System.out.println(headerName + " = " + request.getHeader(headerName));        
         }
         System.out.println( "===== End headers =====\n" );
         
         // opens input stream of the request for reading data
         InputStream inputStream = request.getInputStream();
         
         // opens an output stream for writing file
         FileOutputStream outputStream = new FileOutputStream(saveFile);
         
         byte [] buffer = new byte [BUFFER_SIZE];
         int bytesRead = - 1 ;
         System.out.println( "Receiving data..." );
         
         while ((bytesRead = inputStream.read(buffer)) != - 1 ) {
             outputStream.write(buffer, 0 , bytesRead);
         }
         
         System.out.println( "Data received." );
         outputStream.close();
         inputStream.close();
         
         System.out.println( "File written to: " + saveFile.getAbsolutePath());
         
         // sends response to client
         response.getWriter().print( "UPLOAD DONE" );
     }
}
This servlet handles HTTP POST requests in its doPost() method. There are some important points here in this code:
    • Name of the upload file is retrieved from a HTTP header named as “fileName” – this header is set by the client.
    • We create a saveFile object in order to save the upload file into disk. Its path is constructed from the SAVE_DIR constant and the fileName header. A FileOutputStream object wraps this saveFile to write byte arrays into the file.
    • The most important point is to open an InputStream from the HttpServletRequest in order to read bytes transferred from the client.
    • We use a while loop to repeatedly read byte arrays from the request’s input stream and write them into the saveFile’s output stream. This is trivial.
    • And finally, always close the opened input stream and output stream, then send a response to the client (in this case, a simple text message “UPLOAD DONE”).
Now let’s examine how the client is implemented.  
Head First Servlets and JSP [Kindle version] - This book does not only help you interact with Servlets and JSPs quickly and deeply, it also helps you have a good preparation for the SCWCD/OCPJWCD. Read this book if you want to get certified.


Coding the client program

Following is code of the client program:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
 
/**
  * This program demonstrates how to upload files to a web server
  * using HTTP POST request without any HTML form.
  * @author www.codejava.net
  *
  */
public class NonFormFileUploader {
     static final String UPLOAD_URL = "http://localhost:8080/CodeWeb/ReceiveFileServlet" ;
     static final int BUFFER_SIZE = 4096 ;
 
     public static void main(String[] args) throws IOException {
         // takes file path from first program's argument
         String filePath = args[ 0 ];
         File uploadFile = new File(filePath);
 
         System.out.println( "File to upload: " + filePath);
 
         // creates a HTTP connection
         URL url = new URL(UPLOAD_URL);
         HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
         httpConn.setUseCaches( false );
         httpConn.setDoOutput( true );
         httpConn.setRequestMethod( "POST" );
         // sets file name as a HTTP header
         httpConn.setRequestProperty( "fileName" , uploadFile.getName());
 
         // opens output stream of the HTTP connection for writing data
         OutputStream outputStream = httpConn.getOutputStream();
 
         // Opens input stream of the file for reading data
         FileInputStream inputStream = new FileInputStream(uploadFile);
 
         byte [] buffer = new byte [BUFFER_SIZE];
         int bytesRead = - 1 ;
 
         System.out.println( "Start writing data..." );
 
         while ((bytesRead = inputStream.read(buffer)) != - 1 ) {
             outputStream.write(buffer, 0 , bytesRead);
         }
 
         System.out.println( "Data was written." );
         outputStream.close();
         inputStream.close();
 
         // always check HTTP response code from server
         int responseCode = httpConn.getResponseCode();
         if (responseCode == HttpURLConnection.HTTP_OK) {
             // reads server's response
             BufferedReader reader = new BufferedReader( new InputStreamReader(
                     httpConn.getInputStream()));
             String response = reader.readLine();
             System.out.println( "Server's response: " + response);
         } else {
             System.out.println( "Server returned non-OK code: " + responseCode);
         }
     }
}



The important point here is we use an HttpURLConnection object to send an HTTP POST request to the server at URL of the servlet (identified by the constant UPLOAD_URL) and open the OutputStream of this connection to write byte arrays of the upload file. Path of this file is passed as the first argument of the program. Similarly to the servlet, we use a while loop to read/write byte arrays from/to the file’s input stream/request’s output stream. Finally, we read response from the server after closing both input/output streams by using the input stream of the request.

Testing the application

Deploy the ReceiveFileServlet on a servlet container like Tomcat and start the server. Then run the client program by executing the following command:

java NonFormFileUploader e:\Test\RecordAudio.wav

Here we pass a WAV audio file to be uploaded. The server will produce some output as the following screenshot: server output From this log, we can examine values of all HTTP headers sent from the client. Almost of values are set by Java automatically, except the filename is set from the client manually. And here is the output from the client program: client output   NOTE:
    • Neither the server nor the client is playing with multipart request (which is standard for form-based upload). Note that the request’s content type is set to application/x-www-form-urlencoded instead of multipart/form-data.
    • Thus the client program cannot be applied for the server which accepts multipart request. The server side must be implemented like the ReceiveFileServletdoes.
华为OD机试真题 2026.11.4. 新系统 【河流水系流量评估】 华为OD机试真题 新系统【河流水系流量评估】,提供C语言、Java、C++、Python、Go、JavaScript源码实现,并提供完整思路讲解,以及在线OJ模拟做题。华为OD机试真题 【河流水系流量评估】多语言题解。 阅读详情

相关推荐

CMap数据库学习及结果可视化

CMap是一个生物信息学数据库和工具,旨在通过比较基因表达谱来揭示药物、基因和疾病之间的潜在关联。CMap数据库主要用于寻找药物、化合物和生物过程之间的关系,并用于药物重定位(drug repurposing)和疾病机制研究。

zfyyzhys的博客 5599

Spring AI + GPT-5.5 + Ollama 配置教程:Base URL、超时与流式调用

由于不同 Spring AI、Spring Boot 小版本之间仍可能存在差异,创建项目时应检查 Spring Initializr、Spring AI BOM 和官方兼容矩阵,不要直接复制旧教程中的 Starter 名称和版本号。多人项目最好隔离不同客户端,并在脱敏前提下记录最终 URL、状态码、请求耗时、请求 ID 和模型 ID。Spring AI 接入模型 API,至少要同时确认 Starter、Base URL、请求路径、API Key、模型 ID、连接超时、读取超时和流式客户端这 8 项。

2601_95893075的博客 214

ANSYS_APDL实战入门——从零开始掌握模态分析

本文为ANSYS APDL模态分析实战入门指南,通过一个悬臂梁案例,手把手教你从零开始掌握APDL命令流。内容涵盖从模型创建、材料定义、网格划分到边界条件设置、求解及后处理结果查看的全流程,帮助工程师快速上手结构动力学分析,避免共振风险。

egg99的博客 1128

【JVM】对象内存布局

HotSpot JVM 中,Java 对象内存布局由对象头(12字节,含Mark Word与压缩Klass Pointer)、实例数据及对齐填充构成,总大小为8字节倍数。对象头支持锁状态动态复用,指针压缩使引用仅4字节,但堆超32GB时失效。实例字段按类型优先级重排序以减少间隙,最小对象大小为16字节。通过JOL工具可精准验证布局,理解锁机制、GC、伪共享等底层行为。

2301_79732484的博客 139

ROS2 -Jazzy 一步一步(第一步_工作空间以及编译)

文件夹作用特点是否需要手动创建/维护src存放自己写的 ROS 2 包一个 workspace 可以有多个包需要手动创建build保存编译过程中的中间文件每个包生成对应子目录自动生成,可删除install保存编译完成后的功能包每个包有独立子目录,含可执行文件自动生成,可删除log保存编译日志用于查看错误原因、调试自动生成,不需修改colcon是 ROS 2 推荐使用的构建工具自动处理功能包的依赖和编译顺序一条命令就能编译整个工作空间。

jerrykorea的博客 1380

5G移动网络运维(优化)

5G 网络优化现状 移动通信行业属于技术密集型行业,是国民经济的重要支柱以及整个社会经济运转体系中不可或缺的基础。2019 年年底 5G 开始商用,截止到 2020 年3月,我国三大运营商建设了 16.1 万个 5G 基站,我国成为目前全球 5G 基站最多的国家。预计到 2020 年年底,我国运营商会建设大概 70 万个 5G 基站。基于 5G高频段的特性,信号覆盖距离会低于ins 基站,再加上 5G 万物互联的巨大经济潜力价值需求,后续三大运营商在 5G 基站建设数量上势必会超过当前 LTE 基站数量的

2301_78171382的博客 1323

V8 机制、手写核心函数与 TypeScript 类型体操

或固定初始化(如数组先定长、对象先给全字段)保持类型与形状稳定;这些都比"换框架"更基础。只能处理纯数据(丢函数、Date、RegExp、循环引用报错)。生产级深拷贝要处理:原始值短路、循环引用、V8(Chrome / Node 的 JS 引擎)不是"解释一行跑一行"那么简单,它用。图:V8 执行流程——解释执行 + 热点优化,优化失败会 Deopt 回退。JS 内存自动管理,但"自动"不等于"不会漏"。是"固定间隔最多执行一次"。手写 Promise 是"懂异步"的试金石。是"停下后才执行最后一次",

qq_38468358的博客 323

【WRF-GHG 教程第一期】概述(Overview)

概述(Overview)

WW、forever的博客 508

Spring Boot 数据源与 MyBatis(-Plus) 自定义配置详解

本文详解 Spring Boot 中单数据源环境下 HikariCP 与 MyBatis-Plus 的自定义配置。通过手动声明 SqlSessionFactory,实现下划线转驼峰、日志输出、一级缓存策略等精细化控制。结合 HikariCP 核心参数调优(如最大连接数、连接生命周期),确保高性能与稳定性。适用于仅需访问单一数据库的场景,避免多数据源复杂性,兼顾性能与可维护性。

BADAO_LIUMANG_QIZHI的博客 187

2026年寒武纪数字IC笔试试卷带答案

本文摘要: 该数字IC设计测试卷包含单选题(30分)、波形分析题(15分)、多选题(30分)三类客观题,覆盖时序约束、半导体工艺、状态机、数制转换、同步复位等核心知识点。重点考察:1)跨时钟域处理(如异步FIFO、格雷码应用);2)时序分析(建立/保持时间、时钟约束指令);3)低功耗设计技术(时钟门控、DVFS);4)寒武纪MLU架构特性(张量核、混合精度计算)。解析强调工程实践要点,如异步复位需同步释放、建立时间违例与频率的关联性等。试题难度梯度明显,既包含基础概念辨析(如Moore/Mealy状态机),

Open 222

YOLOv11 改进 - 注意力机制 | HaloNet 局部自注意力 (Local Self-Attention) 以分块交互策略实现高效全局上下文建模

本文介绍了局部自注意力机制(HaloAttention)在YOLOv11中的结合应用。局部自注意力通过关注输入数据局部区域来捕捉特征关系,能降低计算复杂度、增强局部特征捕捉,且可与CNN结合。其计算时先定义局部窗口,再计算注意力权重并加权求和。我们将HaloAttention集成到YOLOv11的检测头中,并进行相关注册和配置。实验表明,改进后的模型在目标检测和实例分割等任务中表现更佳,证明了自注意力模型在传统卷积主导领域的有效性。

魔改工程师的博客 1139

Java EE 进阶:8.MyBatis 操作数据库(入门)(第一弹)

Java EE 进阶:8.MyBatis 操作数据库(入门)(第一弹)

要努力去发光,而不是被照亮~ 108

关于机器人精度的总结(重复精度和绝对精度区分)

机械臂是工业生产中的重要设备,在焊接码垛 以及 非 接触测量等 领域中有 着重要应 用。然而由于机械臂本体制造中存在机械制造公差装配误差导致的运动学参数误差以及电机转角与关节转角间减速比误差等,导致机械臂存在。因此需要对机械臂进行标定,提高机械臂的绝对定位精度。ABB系列某款机器人精度参数表。

大胡子大叔的专栏 1万+

LeetCode Hot 100 二叉树专题(二)3 题(Java)

本篇文章共 3 题:543. 二叉树的直径、102. 二叉树的层序遍历、108. 将有序数组转换为二叉搜索树。 每道题都统一按「① 题目分析 & 解题思路 → ② 常见解法(附代码)及讲解 → ③ 知识点总结」的顺序组织;代码使用 Java 编写,节点定义沿用 LeetCode 默认的 TreeNode。

2401_88612756的博客 351

蓝牙模块HM-10手册

蓝牙模块HM-10手册,该手册对蓝牙模块HM-10进行了详细的介绍和使用方法以及一些AT指令。

锂电池充电器电路设计 里面有电路

锂电池充电器电路设计 里面有电路 3.7V升压到5V电路设计。

Decorator

TaskDecorator 是异步场景下"跨线程传递上下文"的标准方案,主要用于传递 MDC、用户信息、数据源路由等上下文数据,核心价值是让异步任务的日志链路不中断、业务上下文不丢失。TaskDecorator 是 Spring 提供的一个钩子接口,用于在异步任务执行前对 Runnable 进行包装,常用于跨线程传递上下文。如果你在项目中遇到具体的异步上下文传递问题,可以把代码贴出来,我帮你给出最合适的 Decorator 方案 👍。✅ 核心能力:在线程切换时,把"父线程的上下文"搬到"子线程"

wlwork66的博客 101

假人有限元模型

假人模型,车辆碰撞假人有限元模型,适合做乘员安全的研究者利用

数据库乐观锁深度解析:MySQL、PostgreSQL 实战 + Spring Boot 集成指南

Oracle 提供了ORA_ROWSCN伪列(System Change Number),记录最后修改行的 SCN,类似 PostgreSQL 的xmin。实践中通常仍使用 version 字段方案,逻辑与 MySQL 完全相同。-- Oracle:通过 ORA_ROWSCN 实现乐观锁-- 更新时比对 SCN// 自定义注解// AOP 切面@Aspect@Component@Slf4jtry {

yjc_1111的专栏 389

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

JDK 下载安装:装完 Java 提示「不是内部或外部命令」?环境变量没配

JDK 是写 Java 程序必须装的东西。它包含运行 Java 的虚拟机(JRE)和编译 Java 的编译器(javac)——装了它,能跑、.java文件能编译成可执行程序。免费,学习和小规模生产都不花钱。

科小怪的博客 607

C++ 多态详解:作用、原理与实战用法

多态是C++面向对象的核心特性,通过虚函数实现运行期动态绑定,使同一接口在不同对象上表现出不同行为。其核心作用包括统一接口、提升可扩展性、降低耦合、支持运行时分派与批量处理。实现依赖虚函数表(vtable)和虚指针(vptr),需注意虚析构函数、对象切片等陷阱。相比编译期多态(模板),运行期多态灵活性高但有调用开销。合理结合两者,可兼顾代码的灵活性与性能,是构建可扩展、低耦合系统的关键。

2402_85743155的博客 369

java框架大全

java框架大全

qq_39326137的博客 180

SecureRandom做随机源,这个Java随机字符串工具类有3个方法

本文分享一款JDK17环境下的Java随机字符串工具类,内置3个开箱即用的方法,全部采用SecureRandom加密安全随机源,不存在弱随机、可预测、取模偏差等问题。工具类支持默认62字符集随机串、纯数字随机串、自定义字符集随机串三种生成模式,支持Unicode码点级别的字符集处理,兼容Emoji等增补字符,边界处理严格,异常信息明确,适合验证码、邀请码、盐值、随机口令、短链码等场景,源码可直接复制使用。

Java后端 | AI智能体应用实战派 | 电脑技能行家 291

Java实现批量线段相交检测(跨积判定+扫描线优化与踩坑复盘)

【代码】Java实现批量线段相交检测(跨积判定+扫描线优化与踩坑复盘)

m0_64476639的博客 313

Agent 状态栏在上下文中的具体位置

Agent状态栏以user角色消息形式追加至上下文末尾,而非修改system消息,避免破坏KVCache。此举仅为API技术实现,内容由框架自动生成,非真实用户输入,通过<agent_status>标签标识,确保模型获取最新状态且不影响缓存。该设计遵循“动态信息追加、静态信息固定”原则,实现高效、低延迟的状态传递。

lj1109053360的专栏 67

ubuntu安装hadoop系统

本文详细介绍了基于VMware克隆虚拟机搭建三节点Hadoop分布式集群的全过程:使用同一Ubuntu镜像克隆出master、worker1、worker2三台虚拟机,依次配置主机名、固定IP(如192.168.82.10/11/12)、SSH服务及免密登录,确保节点间网络互通。随后安装Java,下载配置Hadoop并分发至各节点,最终初始化启动集群,验证其存储与计算功能,实现高效的大数据环境部署。

qq_43592674的博客 279

Spring事务和事务传播机制

3. 可重复读(REPEATABLE READ): 事务不会读到其他事务对已有数据的修改, 即使其他事务已提交. 也就可以确保同⼀事务多次查询的结果⼀致, 但是其他事务新插⼊的数据, 是可以感知到的. 这也就引发了幻读问题. 可重复读, 是 MySQL 的默认事务隔离级别.p1事务可以认为是⽗事务, 嵌套事务是⼦事务. ⽗事务出现异常, ⼦事务也会回滚, ⼦事务出现异常, 如果不进⾏处理, 也会导致⽗事务回滚.

txxzjmzlh的博客 202

RuoyiOffice 容器化落地:镜像分层、JVM 配额与三探针的联动配置

拆解 RuoyiOffice 上容器的三道坎:多阶段镜像分层、按 cgroup 配额切分 JVM 内存、startup/liveness/readiness 三探针分工,附可复制的 Dockerfile、JVM 参数与 K8s YAML。

2301_78967866的博客 299

读懂 Dart Future:从 async/await 到并发等待

Dart 中的 Future 用于处理异步操作,如网络请求、文件读取等。它表示一次可能延迟完成的计算,成功时返回指定类型值(如 Future<String>),失败时抛出异常。通过 async/await 可以同步式编写异步代码,提升可读性。await 暂停当前函数执行,但不影响事件循环。Future.wait() 可并发等待多个异步任务,timeout() 设置超时限制,catchError() 处理错误。注意:async 不自动开启新线程,耗时计算仍可能阻塞主线程;避免丢弃未处理的 Future,必要时

侯仕奇的博客 344
上一篇: How to automate login a website – Java example
下一篇: Upload files by sending multipart request programmatically
daniel7443
博客等级 码龄24年 32粉丝 1原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值