1. 程式人生 > 實用技巧 >JQuery的ajaxFileUpload的使用--實現ajax上傳檔案

JQuery的ajaxFileUpload的使用--實現ajax上傳檔案

HTML程式碼:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link href="../css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
        <input type="file" id="file" name="file"/><br>
        <
button id="uploadBtn" class="btn btn-primary" type="button" >上傳</button><br> <img src="../img/9.jpg" class="img-circle" style="height: 255px; width:255px"> </body> <script src="../js/jquery-1.7.1.min.js"></script> <!--想要使用ajaxFileUpload外掛必須引入這個js--> <
script src="../js/ajaxfileupload.js"></script> <script> $(()=>{ $('#uploadBtn').click(function () { $.ajaxFileUpload({ url:'../uploadFile', type:'post', fileElementId: "file", //需要上傳的檔案域的ID,即<input type="file">的ID
dataType:'String', success: function(result) { alert(result); $(".img-circle").attr("src","../upload/" + result); } }) }) }) </script> </html>

後臺servlet程式碼:

@WebServlet(name = "UploadFileServlet",value = "/uploadFile")
//必須加此註解 重要!
@MultipartConfig
public class UploadFileServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Part part = request.getPart("file");
        String header = part.getHeader("content-disposition");
        //獲得上傳檔名
        String path = header.substring(header.indexOf("filename=") + 10, header.length() - 1);
        // 獲取檔案的真實路徑
        String realPath = this.getServletContext().getRealPath("/upload");
        String newFileName = generateUploadFileName(getRealName(path));
        File file = new File(realPath);
        //資料夾不存在則建立
        if (!file.exists()) {
            file.mkdirs();
        }

        // 獲取輸入流
        InputStream inputStream = part.getInputStream();
        // 定義輸出流
        FileOutputStream outputStream = new FileOutputStream(new File(file, newFileName));

        // 從輸入流中讀入資料並寫到輸出位元組流中
        int len = -1;
        byte[] bytes = new byte[1024];
        while ((len = inputStream.read(bytes)) != -1) {
            outputStream.write(bytes, 0, len);
        }

        // 關閉資源
        outputStream.close();
        inputStream.close();

        // 刪除臨時檔案
        part.delete();
        //向伺服器返回新檔名
        response.getWriter().print(newFileName);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    public static String getRealName(String path) {
        int index = path.lastIndexOf("\\");
        if (index == -1) {
            index = path.lastIndexOf("/");
        }
        return path.substring(index + 1);
    }
    //傳入舊檔名,獲得新的檔名
    public static String generateUploadFileName(String name){
        String suffixName = name.substring(name.lastIndexOf("."));
        return System.currentTimeMillis() + "_" +(int)(Math.random() * 100000) +suffixName;
    }
}