Home > Java > JavaBase > body text

How to implement file upload in java

王林
Release: 2019-12-05 11:52:16
Original
2681 people have browsed it

How to implement file upload in java

(1) Prepare the front page Upload.html

Form action=Upload file background interface method=”post” enctype=”multipart/form- data”

File input box

<form action="/upload" method="post" enctype="multipart/form-data">
     <input type="file" name="files">
    <input type="submit" value="上传">
</form>
Copy after login

(2) Add the corresponding jar package

How to implement file upload in java

Free online video tutorial sharing: java online video

(3) Prepare to receive the file Servlet

url path must be consistent with the action of the form above

How to implement file upload in java

(4) Write the file upload background code

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws 
ServletException, IOException {
        try {
            // 配置上传参数
            DiskFileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            // 解析请求的内容提取文件数据
            @SuppressWarnings("unchecked")
            List<FileItem> formItems = upload.parseRequest(request);
 
            // 迭代表单数据
            for (FileItem item : formItems) {
                // 处理不在表单中的字段
                if (!item.isFormField()) {
                    String fileName = item.getName();
                    //定义上传文件的存放路径
                    String path = request.getServletContext().getRealPath("/uploadFiles");
                    //定义上传文件的完整路径
                    String filePath = String.format("%s/%s",path,fileName);
                    File storeFile = new File(filePath);
                    // 在控制台输出文件的上传路径
                    System.out.println(filePath);
                    // 保存文件到硬盘
                    item.write(storeFile);
                }
            }
        } catch (Exception ex) {
 
        }
 
    }
Copy after login

(5) Prepare the directory to store the uploaded files, pay attention to keep the path consistent with the above code

How to implement file upload in java

Recommended related articles and tutorials: Getting started with java development

The above is the detailed content of How to implement file upload in java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template