0

我正在开发一个允许用户使用 HttpPost 方法上传图像的应用程序。我使用 MultipartEntity,因此我将库 apache-mime4j-0.6.1.jar、httpclient-4.3.1.jar、httpcore-4.3.1.jar 和 httpmime-4.2.1.jar 添加到我的应用程序中。我的上传代码如下:

public String uploadFile() throws Exception
{
    String result = "";
    try 
    {

            HttpResponse response = null;
            HttpClient httpClient = new DefaultHttpClient();
            HttpPost request = new HttpPost(_url);

            request.setHeader("Accept", "application/json");

            File file=new File(filePath);
            String fileName=file.getName();


            MultipartEntity imageEntity=new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE,null,Charset.forName("UTF-8"));
            imageEntity.addPart("imageName", new StringBody(fileName));
            imageEntity.addPart("image", new FileBody(file, "application/octet-stream"));
            request.setEntity(imageEntity);


            response = httpClient.execute(request);

            InputStream dataStream = response.getEntity().getContent();
            BufferedReader dataReader = new BufferedReader(new InputStreamReader(dataStream));
            String line = "";
            while ((line = dataReader.readLine()) != null) 
                result+=line;

    } 

    catch (Exception e) 
    {

    }

    return result;
}

我从服务器收到响应,但在我的网络服务代码 Request.Files 中没有文件。如果我换行:

MultipartEntity imageEntity=new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE,null,Charset.forName("UTF-8"));

MultipartEntity imageEntity=new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

应用程序正在运行很长时间(大约 3-4 分钟)并引发错误。如果我添加图像,就会出现这种情况。如果我只发送没有 FileBody 的 StringBody,我会收到来自服务器的响应,并且我的 Web 服务代码中的 Request.Files 会正确返回文件计数。如何解决此问题并正确上传图像?有什么建议吗?

4

0 回答 0