gpt4 book ai didi

java - 如何让服务器下载客户端通过 HTTP PUT 请求上传的图像文件?

转载 作者:行者123 更新时间:2023-12-02 08:01:29 26 4
gpt4 key购买 nike

我需要用 Java 实现一个 Web 服务器。 Web 服务器应下载客户端在 HTTP PUT 请求中上传的图像文件。这样做的程序是什么?我应该使用哪些 Java 类?

此外,如果您能推荐一本涵盖这些主题的好书,那就太好了。但现在更重要的是具体问题。

最佳答案

您应该阅读有关 Java servlet 和 servlet 容器的内容。首先实现一个简单的servlet返回“Hello world”字符串。

这是有史以来最短的上传/下载 servlet:

import org.apache.commons.io.IOUtils;

@WebServlet(urlPatterns = {"/test"})
public class DownloadServlet extends HttpServlet {

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
File f = new File("test.txt");
resp.setContentLength((int) f.length());
final FileInputStream input = new FileInputStream(f);
IOUtils.copy(input, resp.getOutputStream());
input.close();
}

@Override
protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
final FileOutputStream output = new FileOutputStream("test.txt");
IOUtils.copy(req.getInputStream(), output);
output.close();
}
}

第一次点击:

$ curl -X PUT -d "Hello, servlet" localhost:8080/test

将给定文本存储在磁盘上某个名为 test.txt 的文件中。然后只需在浏览器中输入 localhost:8080/test 即可。我认为这是一个好的开始。

关于java - 如何让服务器下载客户端通过 HTTP PUT 请求上传的图像文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8840019/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com