Servlet上傳檔案解決中文亂碼問題
阿新 • • 發佈:2021-01-10
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<!--配置xml路徑-->
<servlet>
<servlet-name>UploadServlet</servlet-name>
<servlet-class>ProjectTest.UploadServlet</servlet-class>
</servlet>
<servlet-mapping>
< servlet-name>UploadServlet</servlet-name>
<url-pattern>/uploadServlet</url-pattern>
</servlet-mapping>
</web-app>
<%--
Created by IntelliJ IDEA.
User: 87672
Date: 2021/1/9
Time: 20:13
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
< html>
<head>
<title>上傳</title>
</head>
<body>
<!--建立靜態頁面,如下圖所示-->
<form action="http://localhost:8080/_1_9File_war_exploded/uploadServlet" method="post" enctype="multipart/form-data">
使用者名稱:<input type="text" name="username"><br>
頭像:<input type="file" name="photo"><br>
<input type="submit" value="上傳">
</form>
</body>
</html>
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;
//上傳檔案的程式
public class UploadServlet extends HttpServlet {
/**
* Java上傳檔案
* @param req
* @param resp
* @throws ServletException
* @throws IOException
*/
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1.先判斷上傳的資料是否是多段資料(只有多段資料才是檔案上傳的)
if(ServletFileUpload.isMultipartContent(req)){
//建立FileItemFactory工廠實現類
FileItemFactory fileItemFactory = new DiskFileItemFactory();
//建立用於解析上傳資料的工具類ServletFileUpload類
ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);
//解析上傳的資料,得到每一個表單項FileItem
try {
List<FileItem> list = servletFileUpload.parseRequest(req);
//迴圈判斷每一個表單項是普通型別還是上傳的檔案
for (FileItem fileItem : list) {
if(fileItem.isFormField()){
//普通表單項
System.out.println("表單項的name屬性值:" + fileItem.getFieldName());
//引數UTF-8解決亂碼問題
System.out.println("表單項的value屬性值:" + fileItem.getString("UTF-8"));
}else {
//上傳的檔案
System.out.println("表單項的name屬性值:" + fileItem.getFieldName());
System.out.println("上傳的檔名:" + fileItem.getName());
fileItem.write(new File("e:\\" + fileItem.getName()));
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
問題:從Java程式中可以看出,已經設定編碼字符集為UTF-8,但檔名若包含中文,依舊會出現中文亂碼,若下圖所示
解決方案:必須加上如下程式碼
servletFileUpload.setHeaderEncoding(“UTF-8”);如下圖所示