日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Servlet实现文件上传

發(fā)布時間:2025/3/15 编程问答 34 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Servlet实现文件上传 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

Servlet3.0開始新增了Part接口,專門用來處理文件上傳。

package javax.servlet.http;import java.io.IOException; import java.io.InputStream; import java.util.Collection; public interface Part {public InputStream getInputStream() throws IOException;public String getContentType();//獲得內(nèi)容屬性如image/pngpublic String getName();//獲得input name屬性值與request.getPart參數(shù)值一致public String getSubmittedFileName();//獲得上傳文件名public long getSize();public void write(String fileName) throws IOException;//將上傳內(nèi)容寫入文件public void delete() throws IOException;public String getHeader(String name);//根據(jù)標(biāo)頭名稱返回標(biāo)頭信息public Collection<String> getHeaders(String name);//根據(jù)標(biāo)頭名稱返回標(biāo)頭信息集合public Collection<String> getHeaderNames();//返回標(biāo)頭名稱集合 }

比較重要的幾個方法:

/** * Obtain the content type passed by the browser. * * @return The content type passed by the browser or <code>null</code> if * not defined. */ public String getContentType(); 獲得文件類型信息,如image/jpeg;image/png。

/** * If this part represents an uploaded file, gets the file name submitted * in the upload. Returns {@code null} if no file name is available or if * this part is not a file upload. * * @return the submitted file name or {@code null}. * * @since Servlet 3.1 */ public String getSubmittedFileName(); 獲得上傳文件名稱,如test.jpg

/** * A convenience method to write an uploaded part to disk. The client code * is not concerned with whether or not the part is stored in memory, or on * disk in a temporary location. They just want to write the uploaded part * to a file. * * This method is not guaranteed to succeed if called more than once for * the same part. This allows a particular implementation to use, for * example, file renaming, where possible, rather than copying all of the * underlying data, thus gaining a significant performance benefit. * * @param fileName The location into which the uploaded part should be * stored. Relative locations are relative to {@link * javax.servlet.MultipartConfigElement#getLocation()} * * @throws IOException if an I/O occurs while attempting to write the part */ public void write(String fileName) throws IOException; 上傳文件。

/** * Obtain the size of this part. * * @return The size of the part if bytes */ public long getSize(); 獲得上傳文件大小(字節(jié))。

Demo:

upload.html

<!DOCTYPE html> <html> <head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>upload</title> </head> <body><form action="upload.do" method="post" enctype="multipart/form-data">上傳圖片:<input type="file" name="photo" value="" /><br /><input type="submit" value="上傳" name="upload" /></form> </body> </html>uploadServlet.javaimport javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.Part; import java.io.IOException; import java.io.PrintWriter; import java.time.LocalDate; import java.time.LocalTime; import java.time.format.DateTimeFormatter; //import javax.servlet.annotation.MultipartConfig; //import javax.servlet.annotation.WebServlet;/*** Created by N3verL4nd on 2017/1/9.*/ //@MultipartConfig(location = "D:/JAVA/IdeaProjects/JavaProj/out/artifacts/jspRun_war_exploded/upload") //@WebServlet(name = "uploadServlet", urlPatterns = {"/upload.do"}) public class uploadServlet extends HttpServlet {protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {request.setCharacterEncoding("UTF-8");response.setContentType("text/html;charset=UTF-8");PrintWriter out = response.getWriter();Part part = request.getPart("photo");//獲得上傳文件名稱(實際過程中應(yīng)該重命名自己想要的格式)String filename = part.getSubmittedFileName();//類型檢查如:只要圖片格式文件if (part.getContentType().startsWith("image")) {String finalFileName = getPreFileName() + filename.substring(filename.indexOf('.', 0), filename.length());//寫入文件//part.write(finalFileName);out.println("<h2>" + finalFileName + " 上傳成功</h2>");}else {out.println("<h2>上傳失敗</h2>");}//返回input標(biāo)簽name值(與request.getPart參數(shù)一致)//out.println(part.getName());/*//返回標(biāo)頭名稱集合(如content-disposition;content-type)for (String str : part.getHeaderNames()){out.println(str + "<br />");}*//*//根據(jù)標(biāo)頭名稱返回標(biāo)頭詳細(xì)信息(如form-data; name="photo"; filename="ing.png")for (String str : part.getHeaders("content-disposition")){out.println(str + "<br />");}*//*//返回內(nèi)容類型out.println(part.getContentType() + "<br />");//返回標(biāo)頭信息out.println(part.getHeader("content-disposition") + "<br />");//返回上傳文件大小out.println(part.getSize() + " 字節(jié)");//返回上傳文件名out.println(part.getSubmittedFileName());*///out.println(this.getServletContext().getRealPath("upload"));}//隨機生成文件名private String getPreFileName(){StringBuilder stringBuilder = new StringBuilder();LocalDate date = LocalDate.now();//格式化日期字符串stringBuilder.append(date.format(DateTimeFormatter.BASIC_ISO_DATE));LocalTime time = LocalTime.now().withNano(0);//格式化時間字符串stringBuilder.append(time.format(DateTimeFormatter.ofPattern("HHmmss")));return stringBuilder.toString();}}

上傳服務(wù)器文件名如:20170109214600.png

關(guān)于MultipartConfig:

@MultipartConfig

該注解主要是為了輔助 Servlet 3.0 中 HttpServletRequest 提供的對上傳文件的支持。該注解標(biāo)注在 Servlet 上面,以表示該 Servlet 希望處理的請求的 MIME 類型是 multipart/form-data。另外,它還提供了若干屬性用于簡化對上傳文件的處理。具體如下:

表 5. @MultipartConfig 的常用屬性

屬性名 類型 是否可選 描述
fileSizeThreshold int 當(dāng)數(shù)據(jù)量大于該值時,內(nèi)容將被寫入文件。
location String 存放生成的文件地址。
maxFileSize long 允許上傳的文件最大值。默認(rèn)值為 -1,表示沒有限制。
maxRequestSize long 針對該 multipart/form-data 請求的最大數(shù)量,默認(rèn)值為 -1,表示沒有限制。





轉(zhuǎn)載于:https://www.cnblogs.com/lgh1992314/p/6616243.html

總結(jié)

以上是生活随笔為你收集整理的Servlet实现文件上传的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。