javaweb實現簡單的文件上傳


  • JavaWeb實現文件的上傳


實現用戶將文件上傳到服務里的功能

文件上傳功能解釋:

當用戶在前端網頁點擊文件上傳后,用戶上傳提交的內容會存放到臨時的文件中,我們使用getpart來獲取Part對象,

並通過Part對象獲得流,javaWeb的servlet會獲得用戶所提交的文件並且將文件存放到服務器里


  • 上傳工具類的使用

commons-fileupload-1.2.2.jar

commons-io-2.1.jar

相關jar包的下載地址   點擊下載

將jar包放到WEB-INF的lib目錄下


JSP端 用戶選擇文件並將文件上傳

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>文件上傳</title>
    </head>
    <body>
        <form action="/webtest/upload" method="post" enctype="multipart/form-data">
            <input type="file" name="uploadFile" /> <br/><br/>
            <input type="submit" value="上傳" />
        </form>
    </body>
</html>

Servlet端的代碼 ,獲取上傳的文件並保存在服務器的目錄下 

package com.xyf.web6;
 
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;
 
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
 
@WebServlet("/upload")
@MultipartConfig
 
 
public class UploadServlet extends HttpServlet {
     
   
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        Part part = request.getPart("uploadFile");
        String inputName=part.getName();
        InputStream input=part.getInputStream();
        //想要保存的目標文件的目錄下
        String tagDir=getServletContext().getRealPath("/upload");
        //避免文件名重復使用uuid來避免,產生一個隨機的uuid字符
        String realFileName=UUID.randomUUID().toString();
        OutputStream output=new FileOutputStream(new File(tagDir,realFileName));
        int len=0;
        byte[] buff=new byte[1024*8];
         
        while ((len = input.read(buff)) > -1) {
            output.write(buff, 0, len);
        }
 
        input.close();
        output.close();
        response.setCharacterEncoding("utf-8");
        response.getWriter().print("upload success!!");
     
    }
 
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
 
}

啟動工程之后



選擇上傳的文件點擊上傳,並在服務器目錄下得到上傳的文件




  • 注意事項

1.相關的標注

@MultipartConfig

將該標注配置到服務器Servlet上面,否則會忽略掉文件的內容。並且報錯,錯誤信息如下

嚴重: Servlet.service() for servlet [com.xyf.web6.UploadServlet] in context with path [/webtest] threw exception
java.lang.IllegalStateException: Unable to process parts as no multi-part configuration has been provided

2.客戶端表單中必須指定method=post,因為上傳的文件可能很大,並且指定enctype=multipart/form-data使用上傳文件專門的編碼方式

enctype="multipart/form-data"

客戶端還需要使用<input type="file" 選擇要上傳的文件


3.如果提示當前目錄不存在

會出現文件不存在的錯誤,這個時候需要先去判斷 ,如果不存在就創建,添加以下代碼在servlet里

String uploadFullPath=tagDir;
       //先創建這個文件
       File file=new File(uploadFullPath);
       File ParentFile=file.getParentFile();
       if(!ParentFile.exists())
       {
           ParentFile.mkdirs();//如果文件夾不存在,就創建文件夾
            
       }


當然這樣的上傳方式不是很安全,而且沒有對於文件類型過濾等操作,沒有對惡意代碼進行過濾操作。

我也是剛接觸不久,有錯誤的地方歡迎大家可以指出,以后會相應的對這方便內容進行補充。



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM