javaweb實現文件上傳小功能

本文實例為大傢分享瞭javaweb實現文件上傳的具體代碼,供大傢參考,具體內容如下

1.創建文件上傳頁面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>文件上傳頁面</title>
</head>
<body>
    <form action="${pageContext.request.contextPath}/upload" enctype="multipart/form-data" method="post">
        文件:<input type="file" name="file1"/><br>
        <input type="submit" value="提交"/>
    </form>
</body>
</html>

2.文件上傳Servlet

package com.whoami.servlet;
import com.whoami.utils.UploadUtils;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
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;
import java.io.File;
import java.io.IOException;

@WebServlet(name = "UploadController",value = "/upload")
@MultipartConfig(maxFileSize = 1024*1024*100,maxRequestSize = 1024*1024*200)
public class UploadController extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //實現文件上傳

        // 1.設置亂碼
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        // 2.獲取請求的數據
        Part part = request.getPart("file1");  //獲取文件提交的數據

        // 3.獲取保存文件的路徑 真實路徑
        String uploadPath = request.getServletContext().getRealPath("/WEB-INF/upload");
        File file = new File(uploadPath);
        if(!file.exists()){
            file.mkdir(); //新建upload文件
        }

        // 4.文件上傳(保存)
        //生成唯一文件名 防止文件覆蓋
        String oldName = part.getSubmittedFileName();
        String newName = UploadUtils.newFileName(oldName);
        part.write(uploadPath+"\\"+newName);

        // 5. 響應客戶端 上傳成功!

        response.getWriter().println(part.getSubmittedFileName()+"上傳成功!!");
    }

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

3.生成唯一的文件名

package com.whoami.utils;
import java.util.UUID;
public class UploadUtils {
    public static String newFileName(String filename){
        return UUID.randomUUID().toString().replace("-","")+"_"+filename;
    }
}
//UUID.randomUUID().toString()會
//生成隨意ID(像這樣的6c0766ef-de8d-415a-83bd-fbc3ebd7a306)
//replace("-","")是用空白替換-

4.上傳結果

我把文件存到瞭項目的WEB-INF/upload下面

以上就是本文的全部內容,希望對大傢的學習有所幫助,也希望大傢多多支持WalkonNet。

推薦閱讀: