用于通过http PUT上载文件的Java servlet

时间:2016-01-05 07:54:57

标签: java file http servlets put

由于客户端的一些限制(无POST方法),我们必须通过http PUT上传文件。

有一个线程在stackoverflow上讨论这个,如下所示

File Upload via HTTP PUT Request

但是我们不能使用Spring MVC,所以我不知道如何通过使用AbstractHttpMessageConverter将请求体转换为文件作为上述链接中的答案。

我已经为doPut创建了一个servlet,如下面的代码

public class FileUploader extends HttpServlet
{
    private static Logger   logger  = LogManager.getLogger(FileUploader.class);

/* (non-Javadoc)
 * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 */
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
{
    PrintWriter output = resp.getWriter();
    output.println("GET is not support");
    output.close();
}

@Override
public void doPut(HttpServletRequest req, HttpServletResponse res)
{
    try
    {
        PrintWriter outHTML = res.getWriter();
        outHTML.println("You have put a file!");
        int i;
        InputStream input;
        input = req.getInputStream();
        BufferedInputStream in = new BufferedInputStream(input);
        BufferedReader reader = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8));

        File outputFile = new File("C:\\tmp.txt");
        FileWriter out = new FileWriter(outputFile);
        while ((i = reader.read()) != -1)
        {
            System.out.print(i);
            out.write(i);
        }
        out.close();

        in.close();
        outHTML.println("You have put a file! But nothing else done here.");
        logger.debug("File write ok");
    } catch (Exception e)
    {}
}
}

使用HttpClient的简单http PUT,如下所示

    HttpClientBuilder builder = HttpClientBuilder.create();
    CloseableHttpClient client = builder.build();

    HttpPut put = new HttpPut("");
    put.setURI(URI.create("http://localhost:1010/fileUploader"));
    System.out.println(put.getRequestLine());
    put.setEntity(new FileEntity(new File("C:\\Users\\Administrator\\Desktop\\123.7z")));
    CloseableHttpResponse response = client.execute(put);
    System.out.println(response.getStatusLine());
    System.out.println(EntityUtils.toString(response.getEntity()));

是的,该文件已被PUT并写入C:\作为tmp.txt,但仍然不知道检索文件并获取客户端上传的文件的名称。

感谢任何帮助。

0 个答案:

没有答案