21xrx.com
2024-11-05 19:39:34 Tuesday
登录
文章检索 我的文章 写文章
Java上传文件API实现:
2023-06-13 02:51:32 深夜i     --     --
Java 文件上传 API

Java作为目前主流的后端开发语言,其支持自带的文件上传API可以方便地实现上传文件的功能。下面将详细介绍Java如何接收文件上传的API实现方法。

1.创建表单

表单是提交文件的必要途径,可以通过HTML创建文件上传的表单:


 

 

2.编写Java代码

在Java中可以通过Servlet或者SpringMVC来实现文件上传的功能。

Servlet:


@WebServlet("/upload.java")

@MultipartConfig

public class FileUploadServlet extends HttpServlet {

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

    response.setContentType("text/html");

    

    PrintWriter out = response.getWriter();

    try {

      String contentType = request.getContentType();

      if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0)) {

        DataInputStream in = new DataInputStream(request.getInputStream());

        int formDataLength = request.getContentLength();

        byte dataBytes[] = new byte[formDataLength];

        int byteRead = 0;

        int totalBytesRead = 0;

        while (totalBytesRead < formDataLength) {

          byteRead = in.read(dataBytes, totalBytesRead, formDataLength);

          totalBytesRead += byteRead;

        }

        String file = new String(dataBytes);

        String saveFile = file.substring(file.indexOf("filename=\"") + 10);

        saveFile = saveFile.substring(0, saveFile.indexOf("\n"));

        saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1, saveFile.indexOf("\""));

        int lastIndex = contentType.lastIndexOf("=");

        String boundary = contentType.substring(lastIndex + 1, contentType.length());

        int pos;

        pos = file.indexOf("filename=\"");

        pos = file.indexOf("\n", pos) + 1;

        pos = file.indexOf("\n", pos) + 1;

        pos = file.indexOf("\n", pos) + 1;

        int boundaryLocation = file.indexOf(boundary, pos) - 4;

        int startPos = ((file.substring(0, pos)).getBytes()).length;

        int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;

        File newFile = new File(saveFile);

        FileOutputStream fos = new FileOutputStream(newFile);

        fos.write(dataBytes, startPos, (endPos - startPos));

        fos.flush();

        fos.close();

        out.println("File saved as " + saveFile);

      }

    } catch (Exception e) {

      out.println("Exception in uploading file.");

    }

  }

}

SpringMVC:


@PostMapping("/upload")

@ResponseBody

public String handleFileUpload(@RequestParam("file") MultipartFile file,

              RedirectAttributes redirectAttributes) {

  try {

    byte[] bytes = file.getBytes();

    Path path = Paths.get(file.getOriginalFilename());

    Files.write(path, bytes);

    return "File uploaded successfully!";

  } catch (IOException e) {

    e.printStackTrace();

    return "File upload failed!";

  }

}

3.运行代码

通过以上代码实现文件上传功能,启动Tomcat服务器或Spring Boot项目后,在表单中选择上传的文件并点击上传,终端或网页中会显示上传成功或失败的信息。

以上就是Java接收文件上传的API实现方法,它可以为后端开发工程师提供便利,实现文件上传功能。 3个

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复