當前位置:首頁 » 文件管理 » java文件上傳組件

java文件上傳組件

發布時間: 2023-02-17 19:40:27

java後台文件上傳到資源伺服器上

package com.letv.dir.cloud.util;import com.letv.dir.cloud.controller.DirectorWatermarkController;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import java.io.*;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;/** * Created by xijunge on 2016/11/24 0024. */public class HttpRequesterFile { private static final Logger log = LoggerFactory.getLogger(HttpRequesterFile.class); private static final String TAG = "uploadFile"; private static final int TIME_OUT = 100 * 1000; // 超時時間 private static final String CHARSET = "utf-8"; // 設置編碼 /** * 上傳文件到伺服器 * * @param file * 需要上傳的文件 * @param RequestURL * 文件伺服器的rul * @return 返回響應的內容 * */ public static String uploadFile(File file, String RequestURL) throws IOException {
String result = null;
String BOUNDARY = "letv"; // 邊界標識 隨機生成 String PREFIX = "--", LINE_END = "\r\n";
String CONTENT_TYPE = "multipart/form-data"; // 內容類型 try {
URL url = new URL(RequestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(TIME_OUT);
conn.setConnectTimeout(TIME_OUT);
conn.setDoInput(true); // 允許輸入流 conn.setDoOutput(true); // 允許輸出流 conn.setUseCaches(false); // 不允許使用緩存 conn.setRequestMethod("POST"); // 請求方式 conn.setRequestProperty("Charset", CHARSET); // 設置編碼 conn.setRequestProperty("connection", "keep-alive");
conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);

㈡ java上傳下載文件的第三方控制項jar包,請問是到那裡下載啊

有兩個上傳組件可以下載, Smart Upload 和 FileUpload .
後者很容易找, Struts 也有集成,Smart Upload 在李興華的視頻縮包里有 (具體可以到 verycd 上找下 : mldn 其中的 java web 視頻里,專門講過 SmartUpload )。

㈢ java web斷點續傳,我用的是fileupload來做的上傳。

使用Struts2上傳文件:

Struts文件上傳需要使用File Upload Filter。Filter Upload Filter使用一些默認的規則:

Form中的<s:file name="image"></s:file>標簽對應著Action類中的三個屬性分別是:上傳文件(java.io.File類型),文件名(java.lang.String類型),文件類型(java.lang.String類型,例如:image/jpeg)。命名規約為:

文件:名字與<s:file>標簽中的name屬性一致,這里為:image

文件名:文件 + FileName,這里為:imageFileName

文件類型:文件 + ContentType,這里為:imageContentType

所以針對上述<s:file name="image"></s:file>表示啊的上傳文件的JSP和Action類被別為:

imageUpload.jsp:

[html]view plain

  • <%@pagecontentType="text/html;charset=UTF-8"language="java"%>

  • <%@taglibprefix="s"uri="/struts-tags"%>

  • <html>

  • <head><title>ImageUpload</title></head>

  • <body>

  • <h1>ImageUploadPage</h1>

  • <s:formaction="imageUpload"method="post"enctype="multipart/form-data">

  • <s:filename="image"></s:file>

  • <s:submit></s:submit>

  • </s:form>

  • </body>

  • </html>



  • ImageUploadAction.java:

    [html]view plain

  • packagecom.jpleasure;

  • importcom.opensymphony.xwork2.ActionSupport;

  • importjava.io.File;

  • importjava.io.InputStream;

  • importjava.io.FileInputStream;

  • importjava.io.FileNotFoundException;

  • {

  • privateFileimage;

  • privateStringimageFileName;

  • privateStringimageContentType;

  • publicFilegetImage(){

  • returnimage;

  • }

  • publicvoidsetImage(Fileimage){

  • this.image=image;

  • }

  • publicStringgetImageFileName(){

  • returnimageFileName;

  • }

  • publicvoidsetImageFileName(StringimageFileName){

  • this.imageFileName=imageFileName;

  • }

  • (){

  • returnimageContentType;

  • }

  • publicvoidsetImageContentType(StringimageContentType){

  • this.imageContentType=imageContentType;

  • }

  • publicStringexecute(){

  • if(image!=null){

  • System.out.println("filenameis:"+this.imageFileName);

  • System.out.println("filecontenttypeis:"+this.imageContentType);

  • System.out.println("filelengthis:"+this.image.length());

  • }

  • returnSUCCESS;

  • }

  • }



  • Struts.xml配置文件:

    [html]view plain

  • <actionname="imageUpload"class="com.jpleasure.ImageUploadAction">

  • <result>/success.jsp</result>

  • </action>

  • 這樣當我們選中上傳文件,提交的時候:文件內容會以File類型的方式放在image聲明的變數中。文件的名字將會被放在imageFileName命名的變數中,文件的類型被放在imageContentType命名的變數中。

    文件下載:

    文件下載需要使用一個特殊的Result,stream類型的Result。Stream類型的Result主要用來處理文件下載操作。

    處理原理為:所有的下載文件都是將一個二進制的流寫入到HttpResponse中去。在Action類中定義一個InputSream類型的二進制流,在Result返回給用戶的時候返回給用戶。

    擴展上述的代碼,將上傳來的文件直接下載給用戶:

    ImageUploadAction中需要追加一個InputSream類型的對象,並且指向上傳的文件,代碼如下,紅色部分表示變化:

    [html]view plain

  • packagecom.jpleasure;

  • importcom.opensymphony.xwork2.ActionSupport;

  • importjava.io.File;

  • importjava.io.InputStream;

  • importjava.io.FileInputStream;

  • importjava.io.FileNotFoundException;

  • {

  • privateFileimage;

  • privateStringimageFileName;

  • privateStringimageContentType;

  • =null;

  • (){

  • returnimageInputStream;

  • }

  • publicvoidsetImageInputStream(InputStreamimageInputStream){

  • this.imageInputStream=imageInputStream;

  • }

  • publicFilegetImage(){

  • returnimage;

  • }

  • publicvoidsetImage(Fileimage){

  • this.image=image;

  • }

  • publicStringgetImageFileName(){

  • returnimageFileName;

  • }

  • publicvoidsetImageFileName(StringimageFileName){

  • this.imageFileName=imageFileName;

  • }

  • (){

  • returnimageContentType;

  • }

  • publicvoidsetImageContentType(StringimageContentType){

  • this.imageContentType=imageContentType;

  • }

  • publicStringexecute(){

  • if(image!=null){

  • System.out.println("filenameis:"+this.imageFileName);

  • System.out.println("filecontenttypeis:"+this.imageContentType);

  • System.out.println("filelengthis:"+this.image.length());

  • try{

  • this.imageInputStream=newFileInputStream(image);

  • }catch(FileNotFoundExceptione){

  • e.printStackTrace();

  • }

  • }

  • returnSUCCESS;

  • }

  • }



  • 配置文件為,紅色為變化部分:

    [html]view plain

  • <actionname="imageUpload"class="com.jpleasure.ImageUploadAction">

  • <resultname="success"type="stream">

  • <paramname="contentType">image/pjpeg</param>

  • <paramname="inputName">imageInputStream</param>

  • <paramname="contentDisposition">attachment;filename="image.jpg"</param>

  • <paramname="bufferSize">1024</param>

  • </result>

  • </action>



  • ContentType表示下載文件的類型。

    InputName表示Action類中用來下載文件的欄位的名字。

    ContentDisposition用來控制文件下載的一些信息,包括是否打開另存對話框,下載文件名等。

    BufferSize表示文件下載時使用的緩沖區的大小。

    實際項目開發的考慮:

    控制上傳文件的類型和最大允許上傳文件的size

    使用File Upload Intercepter的參數可盈控制上傳文件的類型和最大允許上傳文件的size。例如:

    [html]view plain

  • <struts>

  • <packagename="myPackage"extends="struts-default">

  • <interceptor-refname="fileUpload">

  • <paramname="maximumSize">2MB</param>

  • <paramname="allowedTypes">text/html,image/jpeg</param>

  • </interceptor-ref>

  • <interceptor-refname="basicStack"/>

  • <actionname="imageUpload"class="com.jpleasure.ImageUploadAction">

  • <resultname="success"type="stream">

  • <paramname="contentType">image/pjpeg</param>

  • <paramname="inputName">imageInputStream</param>

  • <paramname="contentDisposition">

  • attachment;filename="image.jpg"

  • </param>

  • <paramname="bufferSize">1024</param>

  • </result>

  • </action>

  • </package>

  • </struts>



  • 上述表示允許上傳jpeg和html類型的文件,且最大文件上傳size為2MB

    顯示錯誤信息:

    可以使用如下key表示的message來顯示文件上傳出錯的提示信息:

    消息Key 說明

    struts.messages.error.uploading 文件無法正常上傳時的公共錯誤

    struts.messages.error.file.too.large 文件大小超過最大允許size時的錯誤提示

    struts.messages.error.content.type.not.allowed 文件類型不在上傳文件允許類型中的錯誤提示

㈣ java怎麼實現上傳文件到伺服器

  • common-fileupload是jakarta項目組開發的一個功能很強大的上傳文件組件

  • 下面先介紹上傳文件到伺服器(多文件上傳):

  • import javax.servlet.*;

  • import javax.servlet.http.*;

  • import java.io.*;

  • import java.util.*;

  • import java.util.regex.*;

  • import org.apache.commons.fileupload.*;


  • public class upload extends HttpServlet {

  • private static final String CONTENT_TYPE = "text/html; charset=GB2312";

  • //Process the HTTP Post request

  • public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

  • response.setContentType(CONTENT_TYPE);

  • PrintWriter out=response.getWriter();

  • try {

  • DiskFileUpload fu = new DiskFileUpload();

  • // 設置允許用戶上傳文件大小,單位:位元組,這里設為2m

  • fu.setSizeMax(2*1024*1024);

  • // 設置最多隻允許在內存中存儲的數據,單位:位元組

  • fu.setSizeThreshold(4096);

  • // 設置一旦文件大小超過getSizeThreshold()的值時數據存放在硬碟的目錄

  • fu.setRepositoryPath("c://windows//temp");

  • //開始讀取上傳信息

  • List fileItems = fu.parseRequest(request);

  • // 依次處理每個上傳的文件

  • Iterator iter = fileItems.iterator();

  • //正則匹配,過濾路徑取文件名

  • String regExp=".+////(.+)$";

  • //過濾掉的文件類型

  • String[] errorType={".exe",".com",".cgi",".asp"};

  • Pattern p = Pattern.compile(regExp);

  • while (iter.hasNext()) {

  • FileItem item = (FileItem)iter.next();

  • //忽略其他不是文件域的所有表單信息

  • if (!item.isFormField()) {

  • String name = item.getName();

  • long size = item.getSize();

  • if((name==null||name.equals("")) && size==0)

  • continue;

  • Matcher m = p.matcher(name);

  • boolean result = m.find();

  • if (result){

  • for (int temp=0;temp<ERRORTYPE.LENGTH;TEMP++){

  • if (m.group(1).endsWith(errorType[temp])){

  • throw new IOException(name+": wrong type");

  • }

  • }

  • try{

  • //保存上傳的文件到指定的目錄

  • //在下文中上傳文件至資料庫時,將對這里改寫

  • item.write(new File("d://" + m.group(1)));

  • out.print(name+" "+size+"");

  • }

  • catch(Exception e){

  • out.println(e);

  • }

  • }

  • else

  • {

  • throw new IOException("fail to upload");

  • }

  • }

  • }

  • }

  • catch (IOException e){

  • out.println(e);

  • }

  • catch (FileUploadException e){

  • out.println(e);

  • }

  • }

  • }

  • 現在介紹上傳文件到伺服器,下面只寫出相關代碼:

  • sql2000為例,表結構如下:

  • 欄位名:name filecode

  • 類型: varchar image

  • 資料庫插入代碼為:PreparedStatement pstmt=conn.prepareStatement("insert into test values(?,?)");

  • 代碼如下:

  • 。。。。。。

  • try{

  • 這段代碼如果不去掉,將一同寫入到伺服器中

  • //item.write(new File("d://" + m.group(1)));

  • int byteread=0;

  • //讀取輸入流,也就是上傳的文件內容

  • InputStream inStream=item.getInputStream();

  • pstmt.setString(1,m.group(1));

  • pstmt.setBinaryStream(2,inStream,(int)size);

  • pstmt.executeUpdate();

  • inStream.close();

  • out.println(name+" "+size+" ");

  • }

  • 。。。。。。

  • 這樣就實現了上傳文件至資料庫

熱點內容
java返回this 發布:2025-10-20 08:28:16 瀏覽:711
製作腳本網站 發布:2025-10-20 08:17:34 瀏覽:973
python中的init方法 發布:2025-10-20 08:17:33 瀏覽:684
圖案密碼什麼意思 發布:2025-10-20 08:16:56 瀏覽:836
怎麼清理微信視頻緩存 發布:2025-10-20 08:12:37 瀏覽:742
c語言編譯器怎麼看執行過程 發布:2025-10-20 08:00:32 瀏覽:1084
郵箱如何填寫發信伺服器 發布:2025-10-20 07:45:27 瀏覽:313
shell腳本入門案例 發布:2025-10-20 07:44:45 瀏覽:193
怎麼上傳照片瀏覽上傳 發布:2025-10-20 07:44:03 瀏覽:881
python股票數據獲取 發布:2025-10-20 07:39:44 瀏覽:839