新聞中心
隨著互聯(lián)網的快速發(fā)展,圖片的應用越來越廣泛,如何將圖片上傳到數(shù)據(jù)庫已成為當前開發(fā)中必備的技能之一。本文將介紹如何,并為大家詳細展示實現(xiàn)過程。

一、搭建環(huán)境
本文的代碼是基于Eclipse JEE版本來實現(xiàn)的,因此需要先下載并安裝相應的軟件環(huán)境。
二、創(chuàng)建項目
創(chuàng)建一個新的Web項目,設置JRE版本,項目構建技術為Maven,并添加相應的依賴,在pom.xml文件中添加以下代碼:
“`xml
javax.servlet
javax.servlet-api
3.1.0
provided
org.apache.tomcat
tomcat-dbcp
9.0.0.M4
provided
commons-fileupload
commons-fileupload
1.3.1
compile
commons-io
commons-io
2.4
compile
mysql
mysql-connector-java
5.1.26
provided
org.apache.poi
poi
3.17
org.apache.poi
poi-ooxml
3.17
org.apache.poi
poi-ooxml-schemas
3.17
“`
三、創(chuàng)建數(shù)據(jù)庫
創(chuàng)建一個數(shù)據(jù)庫表,用于存儲上傳的圖片,包含以下字段:
id:作為主鍵,自增長
file_name:圖片的文件名
content_type:圖片的類型
file_size:圖片的大小
data:圖片的字節(jié)流
四、編寫上傳Servlet
編寫上傳Servlet,上傳過程中需要進行以下處理:
獲取上傳文件的大小及類型,如果不符合規(guī)則,直接返回錯誤信息;
將上傳文件轉化為字節(jié)流,將字節(jié)流存入數(shù)據(jù)庫中。
以下是具體實現(xiàn)的代碼:
上傳文件:
“`java
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType(“text/html;charset=UTF-8”);
PrintWriter out = response.getWriter();
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (!isMultipart) {
out.println(“文件未上傳!”);
return;
}
String uploadFilePath = request.getServletContext().getRealPath(“/”) + “upload/”;
File uploadFolder = new File(uploadFilePath);
if (!uploadFolder.exists()) {
uploadFolder.mkdirs();
}
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setRepository(uploadFolder);
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding(“UTF-8”);
upload.setSizeMax(MAX_UPLOAD_SIZE);
List items = null;
try {
items = upload.parseRequest(request);
} catch (FileUploadException e) {
e.printStackTrace();
}
if (items == null) {
out.write(“文件未上傳!”);
return;
}
for (FileItem item : items) {
if (item.isFormField()) {
continue;
}
String fileName = item.getName();
if (StringUtils.isEmpty(fileName)) {
continue;
}
if (StringUtils.indexOf(fileName, “/”) >= 0) {
fileName = StringUtils.substringAfterLast(fileName, “/”);
}
if (StringUtils.indexOf(fileName, “\\”) >= 0) {
fileName = StringUtils.substringAfterLast(fileName, “\\”);
}
String contentType = item.getContentType();
if (StringUtils.isEmpty(contentType)) {
continue;
}
InputStream inputStream = null;
try {
long fileSize = item.getSize();
if (StringUtils.isEmpty(fileName) || fileSize > MAX_UPLOAD_SIZE) {
return;
}
byte[] fileBuffer = new byte[(int) fileSize];
inputStream = item.getInputStream();
inputStream.read(fileBuffer, 0, (int) fileSize);
Connection conn = getConnection();
PreparedStatement pstmt = conn.prepareStatement(INSERT_QUERY);
pstmt.setString(1, fileName);
pstmt.setString(2, contentType);
pstmt.setLong(3, fileSize);
pstmt.setBytes(4, fileBuffer);
pstmt.executeUpdate();
if (inputStream != null) {
inputStream.close();
}
if (pstmt != null) {
pstmt.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException ex) {
ex.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
out.print(“文件上傳成功!”);
}
}
“`
五、
本文介紹了如何,并通過詳細的代碼展示了實現(xiàn)過程。如果你也想在項目中實現(xiàn)圖片上傳功能,可以根據(jù)本文的步驟進行操作,相信能夠順利實現(xiàn)。
相關問題拓展閱讀:
- c#如何將圖片保存到mysql數(shù)據(jù)庫,再讀取出來?
c#如何將圖片保存到mysql數(shù)據(jù)庫,再讀取出來?
直接將圖片以二進制流的方式寫入到mysql數(shù)據(jù)庫中,由于數(shù)據(jù)量大,必然會導致服務器的數(shù)據(jù)庫負載很大
我的建議: 采取將圖片存儲在物理磁盤 將相對路徑存儲在數(shù)據(jù)庫中 這樣會減小數(shù)據(jù)庫負載
附上 “上傳圖片” 代碼:
///
/// 上傳圖片
///
升森巧 /// 文件框名稱
/// 上傳文件路徑,url
/// 文件的更大值,單位為字節(jié)
/// 類型:1表示圖片;0表示所有文件
春沖 ///
public static string upfiles(System.Web.UI.HtmlControls.HtmlInputFile files, string paths, long fmax, string ftype)
{
//files 文件上傳組件的名稱;paths 要上傳到的目錄;fmax是上傳文件更大值;ftype是上傳文件的類型
//默認上傳文件更大值100k,文件類型為所有文件
//1為圖片jpg or gif;0為所有文件
//如果文件大于設定值,返回代碼0
//如果文件類型錯誤,返回代碼1
//初始化
long fileMax =;
string fileType = “0”;
string fileTypet = “”;
fileMax = fmax;
fileType = ftype;
if (files.PostedFile.ContentLength > fileMax)
吵鍵 {
return “0”;
//返回錯誤代碼,結束程序
}
fileTypet = System.IO.Path.GetExtension(files.PostedFile.FileName).ToLower();
if (fileType == “1”)
{
if (fileTypet != “.jpg” && fileTypet != “.jpeg” && fileTypet != “.gif”)
{
return “1”;
//返回錯誤代碼,結束程序
}
}
string destdir = System.Web.HttpContext.Current.Server.MapPath(paths);
string filename = CFun.RandomWord() + fileTypet;
string destpath = System.IO.Path.Combine(destdir, filename);
//檢查是否有名稱重復,如果重復就在前面加從0開始的數(shù)字
int i = 0;
string tempfilename = filename;
while (System.IO.File.Exists(destpath))
{
//有重復
tempfilename = i.ToString() + filename;
destpath = System.IO.Path.Combine(destdir, tempfilename);
i = i + 1;
}
//沒有重復,保存文件
files.PostedFile.SaveAs(destpath);
//返回文件名稱
return tempfilename;
}
servlte數(shù)據(jù)庫上傳圖片的介紹就聊到這里吧,感謝你花時間閱讀本站內容,更多關于servlte數(shù)據(jù)庫上傳圖片,使用Servlet實現(xiàn)數(shù)據(jù)庫圖片上傳,c#如何將圖片保存到mysql數(shù)據(jù)庫,再讀取出來?的信息別忘了在本站進行查找喔。
香港服務器選創(chuàng)新互聯(lián),2H2G首月10元開通。
創(chuàng)新互聯(lián)(www.cdcxhl.com)互聯(lián)網服務提供商,擁有超過10年的服務器租用、服務器托管、云服務器、虛擬主機、網站系統(tǒng)開發(fā)經驗。專業(yè)提供云主機、虛擬主機、域名注冊、VPS主機、云服務器、香港云服務器、免備案服務器等。
當前標題:使用Servlet實現(xiàn)數(shù)據(jù)庫圖片上傳(servlte數(shù)據(jù)庫上傳圖片)
當前URL:http://www.dlmjj.cn/article/djpcdjh.html


咨詢
建站咨詢
