【Java基礎】--上傳檔案
專案中常常涉及到檔案上傳的功能,如圖所示,我們上傳一個 2.jpg的圖片檔案,
上傳成功後顯示上傳的圖片源路徑,圖片上傳到D盤根目錄下面:
要實現該功能,我們需要引用如下的jar包:
commons-fileupload-1.1.1.jar
commons-io-1.2.jar
如圖所示:
右鍵專案-Build Path - Add External Archives-選中需要新增的jar包(注意不是zip哦),jar即可引用成功。
上傳使用的servlet如下,FileUploadServlet:
<span style="font-family:Microsoft YaHei;font-size:14px;">package com.bjpowernode.drp.basedata.web;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
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 FileUploadServlet extends HttpServlet {
/**
* Destruction of the servlet. <br>
*/
private String uploadPath = "D:\\addnetFile\\"; // 用於存放上傳檔案的目錄
private File tempPath =new File("D:\\addnetFile\\tmp\\"); // 用於存放臨時檔案的目錄
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* 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
*/
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException{
res.setContentType( "text/html; charset=GB2312");
PrintWriter out=res.getWriter();
System.out.println(req.getContentLength());
System.out.println(req.getContentType());
DiskFileItemFactory factory = new DiskFileItemFactory();
// maximum size that will be stored in memory
factory.setSizeThreshold(4096);
// the location for saving data that is larger than getSizeThreshold()
factory.setRepository(new File("d:\\File\\addnetFile\\temp"));
ServletFileUpload upload = new ServletFileUpload(factory);
// maximum size before a FileUploadException will be thrown
upload.setSizeMax(1000000);
try{
List fileItems = upload.parseRequest(req);
// assume we know there are two files. The first file is a small
// text file, the second is unknown and is written to a file on
// the server
Iterator iter = fileItems.iterator();
// 正則匹配,過濾路徑取檔名
String regExp=".+\\\\(.+)$";
// 過濾掉的檔案型別
String[] errorType={".exe",".com",".cgi",".asp"};
Pattern p = Pattern.compile(regExp);
while (iter.hasNext()) {
FileItem item = (FileItem)iter.next();
//忽略其他不是檔案域的所有表單資訊
if (!item.isFormField()) {
String name = item.getName();
long size = item.getSize();
if((name==null||name.equals("")) && size==0)
continue;
Matcher m = p.matcher(name);
boolean result = m.find();
if (result){
for (int temp=0;temp<errorType.length;temp++){
if (m.group(1).endsWith(errorType[temp])){
throw new IOException(name+": wrong type");
}
}
try{
// 儲存上傳的檔案到指定的目錄
// 在下文中上傳檔案至資料庫時,將對這裡改寫
item.write(new File("d:\\" + m.group(1)));
out.print(name+" "+size+"<br>");
}
catch(Exception e){
out.println(e);
}
}
else
{
throw new IOException("fail to upload");
}
}
}
}
catch (IOException e){
out.println(e);
}
catch (FileUploadException e){
out.println(e);
}
// 儲存上傳的檔案到指定的目錄
// 在下文中上傳檔案至資料庫時,將對這裡改寫
}
/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occure
*/
public void init() throws ServletException {
// Put your code here
}
}
</span>
頁面test_upload.html程式碼:
<span style="font-family:Microsoft YaHei;font-size:14px;"><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>index.html</title>
<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/item/FileUploadServlet" method="post"
enctype="multipart/form-data" name="form1">
<input type="file" name="file">
<input type="submit" name="Submit" value="upload">
</form>
<form action="./servlet/HelloWord" method="post">
<input type="submit" />
</form>
<form name="uploadform" method="POST" action="./servlet/item/FileUploadServlet"
ENCTYPE="multipart/form-data">
<table border="1" width="450" cellpadding="4" cellspacing="2"
bordercolor="#9BD7FF">
<tr>
<td width="100%" colspan="2">
<input name="x" size="40" type="file">
</td>
</tr>
<tr>
<td width="100%" colspan="2">
<input name="y" size="40" type="file">
</td>
</tr>
<tr>
<td width="100%" colspan="2">
<input name="z" size="40" type="file">
</td>
</tr>
</table>
<br />
<br />
<table>
<tr>
<td align="center">
<input name="upload" type="submit" value="��ʼ�ϴ�" />
</td>
</tr>
</table>
</form>
</body>
</html></span>
web.xml:
<span style="font-family:Microsoft YaHei;font-size:14px;"> <servlet>
<servlet-name>FileUploadServlet</servlet-name>
<servlet-class>com.bjpowernode.drp.basedata.web.FileUploadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FileUploadServlet</servlet-name>
<url-pattern>/servlet/item/FileUploadServlet</url-pattern>
</servlet-mapping></span>
把這些程式碼整合到一起,即可實現檔案的上傳功能。
相關文章
- Linux基礎命令---mput上傳ftp檔案LinuxFTP
- 檔案上傳之三基於flash的檔案上傳
- Java Web 檔案上傳JavaWeb
- JAVA檔案上傳下載Java
- Java如何上傳大檔案Java
- Java檔案上傳細講Java
- Java大檔案上傳、分片上傳、多檔案上傳、斷點續傳、上傳檔案minio、分片上傳minio等解決方案Java斷點
- java上傳檔案跟批量下載檔案Java
- php檔案上傳之多檔案上傳PHP
- Java 中的 GraphQL 上傳檔案Java
- 『動善時』JMeter基礎 — 15、使用JMeter實現檔案上傳JMeter
- 使用java的MultipartFile實現layui官網檔案上傳實現全部示例,java檔案上傳JavaUI
- 單個檔案上傳和批量檔案上傳
- java檔案上傳到伺服器Java伺服器
- Java檔案上傳如何實現呢?Java
- java 上傳 下載檔案工具類Java
- Java Web之SpringMVC 上傳檔案JavaWebSpringMVC
- 檔案上傳
- SpringMVC 單檔案上傳與多檔案上傳SpringMVC
- SpringBoot基礎實戰系列(三)springboot單檔案與多檔案上傳Spring Boot
- Java上傳檔案到ftp伺服器JavaFTP伺服器
- 前端大檔案上傳/分片上傳前端
- JAVA實現大檔案分片上傳斷點續傳Java斷點
- Flask——檔案上傳Flask
- PHP上傳檔案PHP
- JavaScript 檔案上傳JavaScript
- Git上傳檔案Git
- YII檔案上傳
- 檔案上傳概述
- beego上傳檔案Go
- 上傳檔案流程
- 上傳EXCLE檔案
- PHP 檔案上傳PHP
- 檔案上傳漏洞
- Jumpserver基礎運維-02檔案傳輸Server運維
- Java SE 檔案上傳和檔案下載的底層原理Java
- MVC檔案上傳 - 使用Request.Files上傳多個檔案MVC
- .NET Core 如何上傳檔案及處理大檔案上傳