javaWeb實(shí)現(xiàn)簡(jiǎn)單文件上傳
本文實(shí)例為大家分享了javaWeb實(shí)現(xiàn)簡(jiǎn)單文件上傳的具體代碼,供大家參考,具體內(nèi)容如下
1.先導(dǎo)入兩個(gè)包:commons-fileupload-1.3.3.jar,commons-io-2.6.jar。
2.前端頁(yè)面代碼
<form action="upLoadfile.do" method="post" ?? ??? ?enctype="multipart/form-data"> ?? ??? ?<input type="text" name="username" /><br>? ?? ??? ?<input type="file" name="userimg" /><br>? ?? ??? ?<input type="submit" value="提交" /> </form>
2.Servlet代碼
package com.uploadtest.upload; ? import java.io.File; import java.io.IOException; import java.util.List; import java.util.UUID; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; 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.FileUploadBase; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; ? /** ?* Servlet implementation class upLoadfile ?*/ @WebServlet("/upLoadfile.do") public class upLoadfile extends HttpServlet { ?? ?private static final long serialVersionUID = 1L; ? ?? ?/** ?? ? * @see HttpServlet#HttpServlet() ?? ? */ ?? ?public upLoadfile() { ?? ??? ?super(); ?? ??? ?// TODO Auto-generated constructor stub ?? ?} ? ?? ?/** ?? ? * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse ?? ? * ? ? ?response) ?? ? */ ?? ?protected void doGet(HttpServletRequest request, HttpServletResponse response) ?? ??? ??? ?throws ServletException, IOException { ?? ??? ?// TODO Auto-generated method stub ?? ??? ?response.getWriter().append("Served at: ").append(request.getContextPath()); ?? ?} ? ?? ?/** ?? ? * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse ?? ? * ? ? ?response) ?? ? */ ?? ?protected void doPost(HttpServletRequest request, HttpServletResponse response) ?? ??? ??? ?throws ServletException, IOException { ?? ??? ?String saveFileName = ""; // ?? ??? ?String oldFileName = ""; // 直接由item.getNam()獲取的文件名,有可能獲取的是路徑,也為了避免重名覆蓋,所以要對(duì)它進(jìn)行處理 ?? ??? ?String newFileName = ""; // 對(duì)源文件名進(jìn)行處理后的名字 ?? ??? ?// 借助工具解析commons-fileupload smartupload(在項(xiàng)目中導(dǎo)入了jar包) ?? ??? ?// 判斷傳遞的是否是文件類型,判斷form的enctype的屬性值是否是multipart/form-data ?? ??? ?boolean isMultipart = ServletFileUpload.isMultipartContent(request); ?? ??? ?if (isMultipart) { ?? ??? ??? ?// 創(chuàng)建FileItem對(duì)象的工廠 ?? ??? ??? ?DiskFileItemFactory factory = new DiskFileItemFactory(); ?? ??? ??? ?// 獲取Servlet上下文 ?? ??? ??? ?ServletContext servletContext = null; ?? ??? ??? ?servletContext = this.getServletConfig().getServletContext(); ?? ??? ??? ?// 獲取臨時(shí)文件夾 ?? ??? ??? ?String str = "javax.servlet.context.tempdir"; ?? ??? ??? ?File repository = (File) servletContext.getAttribute(str); ?? ??? ??? ?factory.setRepository(repository); ?? ??? ??? ?// 創(chuàng)建文件上傳處理器 ?? ??? ??? ?ServletFileUpload upload = new ServletFileUpload(factory); ?? ??? ??? ?// 解決中文亂碼 ?? ??? ??? ?upload.setHeaderEncoding("utf-8"); ?? ??? ??? ?// 解析request獲取上傳的參數(shù) ?? ??? ??? ?try { ?? ??? ??? ??? ?// 使用ServletFileUpload解析器解析上傳數(shù)據(jù),解析結(jié)果返回的是一個(gè)List<FileItem>集合,每一個(gè)FileItem對(duì)應(yīng)一個(gè)Form表單的輸入項(xiàng) ?? ??? ??? ??? ?List<FileItem> items = upload.parseRequest(request); ?? ??? ??? ??? ?// 解決上傳文件名的中文亂碼 ?? ??? ??? ??? ?upload.setHeaderEncoding("UTF-8"); ?? ??? ??? ??? ?// 處理參數(shù) ?? ??? ??? ??? ?for (FileItem item : items) { ?? ??? ??? ??? ??? ?// 判斷是否為Form的表單域,即判斷是否為普通的數(shù)據(jù),若不是則為文件。 ?? ??? ??? ??? ??? ?if (item.isFormField()) { ?? ??? ??? ??? ??? ??? ?String name = item.getFieldName(); ?? ??? ??? ??? ??? ??? ?// 解決普通輸入項(xiàng)的數(shù)據(jù)的中文亂碼問題 ?? ??? ??? ??? ??? ??? ?String value = item.getString("UTF-8"); ?? ??? ??? ??? ??? ??? ?// value = new String(value.getBytes("iso8859-1"),"UTF-8"); ?? ??? ??? ??? ??? ??? ?//System.out.println(name + "=" + value); ?? ??? ??? ??? ??? ?} else { ?? ??? ??? ??? ??? ??? ?// 設(shè)置上傳單個(gè)文件的大小的最大值,目前是設(shè)置為1024*1024*10字節(jié),也就是10MB ?? ??? ??? ??? ??? ??? ?upload.setFileSizeMax(1024 * 1024 * 10); ?? ??? ??? ??? ??? ??? ?// 寫入文件 ?? ??? ??? ??? ??? ??? ?// 此處本項(xiàng)目在服務(wù)器中的路徑,為絕對(duì)路徑,也可以根據(jù)需要存入到其他路徑 ?? ??? ??? ??? ??? ??? ?String rootPath = servletContext.getRealPath("http://"); ?? ??? ??? ??? ??? ??? ?// File.separator(相當(dāng)于添加了一個(gè)分隔符),在Windows下的路徑分隔符(\)和在Linux下的路徑分隔符(/)是不一樣的,當(dāng)直接使用絕對(duì)路徑時(shí),跨平臺(tái)會(huì)報(bào)異常?? ??? ??? ??? ??? ??? ? ?? ??? ??? ??? ??? ??? ?String savePath = rootPath + File.separator + "upload"; ?? ??? ??? ??? ??? ??? ?/* ?此處我是將文件保存在服務(wù)器上的,這樣的話如果重寫部署一次服務(wù)器,之前上傳的文件就會(huì)刪除 ?? ??? ??? ??? ??? ??? ? ?如果想永久保存上傳的文件,可以設(shè)置一個(gè)其他絕對(duì)路徑,如:E:\eclipse-workspace\JAVAWeb\JSPUploadTest\WebContent\fileByupload。*/?? ??? ??? ??? ??? ??? ?? ?? ??? ??? ??? ??? ??? ?// String savePath = "E:\\eclipse-workspace\\JAVAWeb\\JSPUploadTest\\fileByupload"; ? ?? ??? ??? ??? ??? ??? ?File fileSaveFolder = new File(savePath); ?? ??? ??? ??? ??? ??? ?// 如果不存在該文件夾則創(chuàng)建 ?? ??? ??? ??? ??? ??? ?if (!fileSaveFolder.exists()) { ?? ??? ??? ??? ??? ??? ??? ?fileSaveFolder.mkdir(); ?? ??? ??? ??? ??? ??? ?} ?? ??? ??? ??? ??? ??? ?oldFileName = item.getName(); ?? ??? ??? ??? ??? ??? ?newFileName = processFileName(oldFileName); ?? ??? ??? ??? ??? ??? ?saveFileName = savePath + File.separator + newFileName; ?? ??? ??? ??? ??? ??? ?// 存儲(chǔ)文件 ?? ??? ??? ??? ??? ??? ?File uploadedFile = new File(saveFileName); ?? ??? ??? ??? ??? ??? ?item.write(uploadedFile); ?? ??? ??? ??? ??? ?} ?? ??? ??? ??? ?} ?? ??? ??? ??? ?request.setAttribute("message", "文件上傳成功!"); ?? ??? ??? ?} catch (FileUploadBase.FileSizeLimitExceededException e) { ?? ??? ??? ??? ?e.printStackTrace(); ?? ??? ??? ??? ?request.setAttribute("message", "照片大小不能超過(guò)10M"); ?? ??? ??? ??? ?request.getRequestDispatcher("Show.jsp").forward(request, response); ?? ??? ??? ??? ?return; ?? ??? ??? ?} catch (FileUploadException e) { ?? ??? ??? ??? ?// TODO Auto-generated catch block ?? ??? ??? ??? ?e.printStackTrace(); ?? ??? ??? ?} catch (Exception e) { ?? ??? ??? ??? ?// TODO Auto-generated catch block ?? ??? ??? ??? ?e.printStackTrace(); ?? ??? ??? ?} ?? ??? ??? ?request.setAttribute("saveFileName", saveFileName); ?? ??? ??? ?request.setAttribute("newFileName", newFileName); ?? ??? ??? ?request.getRequestDispatcher("Show.jsp").forward(request, response); ?? ??? ?} ?? ?} ? ?? ?// 對(duì)文件名進(jìn)行處理 ?? ?private String processFileName(String oldFileName) { ?? ??? ?// 補(bǔ)充:對(duì)于 item.getName()有的瀏覽器會(huì)返回文件名,而有的瀏覽器會(huì)返回“路徑”+“文件名”,針對(duì)后者我們需要通過(guò)“字符串截取”獲取文件名 ?? ??? ?// 例如會(huì)出現(xiàn)這樣的情況:item.getName():C:\Users\Desktop\備忘錄.txt ?? ??? ?String tempFileName = ""; ?? ??? ?int index = oldFileName.lastIndexOf("\\"); ?? ??? ?if (index != -1) { ?? ??? ??? ?// subString(x)是從字符串的第x個(gè)字符截取 ?? ??? ??? ?tempFileName = oldFileName.substring(index + 1); ?? ??? ?} ?? ??? ?// 為防止文件覆蓋的現(xiàn)象發(fā)生,要為上傳文件產(chǎn)生一個(gè)唯一的文件名 ?? ??? ?return UUID.randomUUID().toString() + "_" + tempFileName; ?? ?} }
3.圖片展示
<p>${message}</p> ? <img id="picture" src="upload/${newFileName}" width="200px" height="200px" alt="不是圖片">
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- JavaWeb實(shí)現(xiàn)文件上傳下載功能實(shí)例解析
- JavaWeb實(shí)現(xiàn)文件上傳下載功能實(shí)例詳解
- JavaWeb文件上傳下載實(shí)例講解(酷炫的文件上傳技術(shù))
- JavaWeb項(xiàng)目實(shí)現(xiàn)文件上傳動(dòng)態(tài)顯示進(jìn)度實(shí)例
- JavaWeb實(shí)現(xiàn)多文件上傳及zip打包下載
- JavaWeb中struts2實(shí)現(xiàn)文件上傳下載功能實(shí)例解析
- JavaWeb實(shí)現(xiàn)文件上傳與下載的方法
- javaweb實(shí)現(xiàn)文件上傳示例代碼
- JavaWeb實(shí)現(xiàn)文件上傳與下載實(shí)例詳解
- JavaWeb文件上傳與下載功能解析
相關(guān)文章
如何通過(guò)Java生成一個(gè)隨機(jī)數(shù)
當(dāng)我們需要在Java中生成隨機(jī)數(shù)時(shí),可以借助JDK中提供的Random類來(lái)實(shí)現(xiàn),通過(guò)使用Random類,我們可以輕松地生成各種類型的隨機(jī)數(shù),下面我們就來(lái)看看如何利用Random類生成隨機(jī)數(shù)吧2023-09-09MyBatis批量插入數(shù)據(jù)過(guò)程解析
這篇文章主要介紹了MyBatis批量插入數(shù)據(jù)過(guò)程解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-08-08java8 統(tǒng)計(jì)字符串字母?jìng)€(gè)數(shù)的幾種方法總結(jié)(推薦)
下面小編就為大家分享一篇java8 統(tǒng)計(jì)字符串字母?jìng)€(gè)數(shù)的幾種方法總結(jié)(推薦),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)吧2017-11-11詳解Spring batch 入門學(xué)習(xí)教程(附源碼)
本篇文章主要介紹了Spring batch 入門學(xué)習(xí)教程(附源碼),小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-11-11java比較器Comparable接口與Comaprator接口的深入分析
本篇文章是對(duì)java比較器Comparable接口與Comaprator接口進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-06-06Java導(dǎo)出excel時(shí)合并同一列中相同內(nèi)容的行思路詳解
這篇文章主要介紹了Java導(dǎo)出excel時(shí)合并同一列中相同內(nèi)容的行,需要的朋友可以參考下2018-06-06java中ArrayList與LinkedList對(duì)比詳情
這篇文章主要通過(guò)實(shí)例對(duì)Java中ArrayList與LinkedList進(jìn)行了對(duì)比,需要的朋友可以參考下2017-04-04