Home Web Front-end JS Tutorial Servlet+Jsp implements the specific ideas and code for uploading pictures or files

Servlet+Jsp implements the specific ideas and code for uploading pictures or files

Dec 24, 2016 pm 05:27 PM

现在不管是博客论坛还是企业办公,都离不开资源的共享。通过文件上传的方式,与大家同分享,从而达到大众间广泛的沟通和交流,我们既可以从中获得更多的知识和经验,也能通过他人的反馈达到自我改进和提升的目的。

下面我就为大家介绍 web项目中的这一上传功能,那么文件是如何从本地发送到服务器的呢?看我慢慢道来: 
首先,我们创建一个新的web工程,在工程的WebRoot目录下新建一个upload文件夹,这样当我们将该工程部署到服务器上时,服务器便也生成个upload文件夹,用来存放上传的资源。

然后,在WebRoot目录下新建一个jsp文件,主要实现的作用就是选择上传的文件,提交至servlet来进行处理 
详细代码如下:一个form将文件信息通过post方式传送到指定的servlet 

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> 
<% 
String path = request.getContextPath(); 
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 
%> 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
<html> 
<head> 
<base href="<%=basePath%>"> 
<title>My JSP &#39;upload.jsp&#39; starting page</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="/upload/UpLoad" method="post" enctype="multipart/form-data"> 
请选择上传的图片或文件:<input type="file" name="fileName"/><input type="submit" value="上传"/> 
</form> 
</body> 
</html>
Copy after login

可以看到,我们将数据提交到工程下的upload/UpLoad。
之后,我们就来编写这个servlet——UpLoad.java

package load; 
import java.io.File; 
import java.io.IOException; 
import java.io.PrintWriter; 
import java.util.List; 
import javax.servlet.ServletContext; 
import javax.servlet.ServletException; 
import javax.servlet.http.HttpServlet; 
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse; 
import org.apache.commons.fileupload.FileItem; 
import org.apache.commons.fileupload.FileUploadException; 
import org.apache.commons.fileupload.disk.DiskFileItemFactory; 
import org.apache.commons.fileupload.servlet.ServletFileUpload; 
public class UpLoad extends HttpServlet { 
@SuppressWarnings("unchecked") 
@Override 
protected void service(HttpServletRequest req, HttpServletResponse resp) 
throws ServletException, IOException { 
req.setCharacterEncoding("utf-8"); 
resp.setContentType("text/html;charset=utf-8"); 
//为解析类提供配置信息 
DiskFileItemFactory factory = new DiskFileItemFactory(); 
//创建解析类的实例 
ServletFileUpload sfu = new ServletFileUpload(factory); 
//开始解析 
sfu.setFileSizeMax(1024*400); 
//每个表单域中数据会封装到一个对应的FileItem对象上 
try { 
List<FileItem> items = sfu.parseRequest(req); 
//区分表单域 
for (int i = 0; i < items.size(); i++) { 
FileItem item = items.get(i); 
//isFormField为true,表示这不是文件上传表单域 
if(!item.isFormField()){ 
ServletContext sctx = getServletContext(); 
//获得存放文件的物理路径 
//upload下的某个文件夹 得到当前在线的用户 找到对应的文件夹 

String path = sctx.getRealPath("/upload"); 
System.out.println(path); 
//获得文件名 
String fileName = item.getName(); 
System.out.println(fileName); 
//该方法在某些平台(操作系统),会返回路径+文件名 
fileName = fileName.substring(fileName.lastIndexOf("/")+1); 
File file = new File(path+"\\"+fileName); 
if(!file.exists()){ 
item.write(file); 
//将上传图片的名字记录到数据库中 

resp.sendRedirect("/upload/ok.html"); 
} 
} 
} 
} catch (Exception e) { 
e.printStackTrace(); 
} 

} 
}
Copy after login

因为已对 代码做了详细的注释,所以相信大家也能基本上传的这个过程。要注意的一点是解析实例空间大小的设置。我们希望上传的文件不会是无限大,因此,设置

.setFileSizeMax(1024*400);
Copy after login

在这儿我们也可以将其设置成一个条件,当文件大于最大值时向页面 提交错误提示。此外,也可以读取选择文件的后缀来筛选出可以上传的类型。这些代码大家自己扩展,不再细谈。

通过servlet, 将正确的文件传送到服务端的upload文件夹中。这儿要注意,如果以后将工程从tomcat移除后,这些文件就会被自动删除。

上传结束之后,使页面转到上传成功页面ok.html。 当用户看到此页面时,说明你已实现文件的上传功能。


更多Servlet+Jsp实现图片或文件的上传功能具体思路及代码相关文章请关注PHP中文网!


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

How to implement panel drag and drop adjustment function similar to VSCode in front-end development? How to implement panel drag and drop adjustment function similar to VSCode in front-end development? Apr 04, 2025 pm 02:06 PM

Explore the implementation of panel drag and drop adjustment function similar to VSCode in the front-end. In front-end development, how to implement VSCode similar to VSCode...

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

See all articles