【问题标题】:How to retrieve file contents to upload in API? Solved如何检索要在 API 中上传的文件内容?解决了
【发布时间】:2015-01-25 07:30:49
【问题描述】:

我遇到了尝试使用文件参数上传内容的问题...

我有获取文件字符串的想法,但我意识到我需要获取文件的内容。如何检索文件内容并上传到指定站点?

编辑:设法找到问题

解决办法如下:

        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            HttpPost httppost = new HttpPost("https://api.teknik.io/upload/post");

            FileBody bin = new FileBody(new File("C:/Users/hp/Desktop/hid.txt"));

            HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("file", bin).build();


            httppost.setEntity(reqEntity);

            System.out.println("executing request " + httppost.getRequestLine());
            CloseableHttpResponse response = httpclient.execute(httppost);
            try {
                System.out.println("----------------------------------------");
                System.out.println(response.getStatusLine());
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    System.out.println("Response content length: " + resEntity.getContentLength());
                }
                System.out.println(EntityUtils.toString(resEntity));
                EntityUtils.consume(resEntity);
            } finally {
                response.close();
            }
        } finally {
            httpclient.close();
        }

它返回: HTTP/1.1 200 正常 响应内容长度:119 [{“结果”: {"file":{"name":"rB8mlB.txt","url":"https://u.teknik.io/rB8mlB.txt","type":"inode/x-empty","size ":0}}}]

我设法让它在 pdf 文件上工作,但 txt 文件有问题 HTTP/1.1 200 正常 响应内容长度:126 [{"results":{"file":{"name":"RfWjkg.pdf","url":"https://u.teknik.io/RfWjkg.pdf","type":"application/pdf ","尺寸":341852}}}]

【问题讨论】:

    标签: java http post file-upload http-post


    【解决方案1】:

    使用 MultipartRequest jar 文件。

    import javax.servlet.http.*;
    import javax.servlet.*;
    import java.io.*;
    import java.util.*;
    import com.oreilly.servlet.*;
    public class UploadServlet extends HttpServlet
    {
    
    public void service(HttpServletRequest req, HttpServletResponse res) throws IOException , ServletException
    {
        res.setContentType("text/html");
        PrintWriter out=res.getWriter();
        MultipartRequest mpr=new MultipartRequest(req,getServletContext().getRealPath("file"),500*1024*1024);
        out.println("<html><body><h3>File Uploaded<h3></html></body>");
    }
    }
    

    在上传按钮上调用这个 servlet。

    【讨论】:

      猜你喜欢
      • 2020-05-24
      • 2011-04-21
      • 2014-04-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多