欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

javaWeb實(shí)現(xiàn)簡(jiǎn)單文件上傳

 更新時(shí)間:2022年06月22日 10:35:28   作者:學(xué)以致用HT  
這篇文章主要為大家詳細(xì)介紹了JAVAWeb實(shí)現(xiàn)簡(jiǎn)單文件上傳,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下

本文實(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í)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論