【问题标题】:Change the name of a file right before uploaded to server在上传到服务器之前更改文件的名称
【发布时间】:2011-11-30 15:34:40
【问题描述】:

我需要以特定名称将图像上传到我的服务器,但理想情况下,我仍希望将图像以原始文件名存储在设备上。这是我尝试过的:

myImageFile.renameTo(new File("mobileimage.jpg"));

但是当文件上传到服务器时,它似乎没有我的新名字。以下是将图片上传到服务器的完整代码:

        DefaultHttpClient mHttpClient;
    HttpParams params = new BasicHttpParams();
    params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    mHttpClient = new DefaultHttpClient(params);

    try {
        myImageFile.renameTo(new File("mobileimage.jpg"));

        HttpPost httppost = new HttpPost("http://mywebsite/mobile/image");

        MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);  
        multipartEntity.addPart("userID", new StringBody(Constants.userID));
        multipartEntity.addPart("uniqueMobileID", new StringBody(Constants.uniqueMobileID));
        multipartEntity.addPart("userfile", new FileBody(myImageFile));
        httppost.setEntity(multipartEntity);

        HttpResponse response = mHttpClient.execute(httppost);
        String responseBody = EntityUtils.toString(response.getEntity());

        Log.d(TAG, "response: " + responseBody);
        return responseBody;

    } catch (Exception e) {
       Log.d(TAG, e.getMessage());
    }

如何更改文件名?

【问题讨论】:

    标签: android image file


    【解决方案1】:

    使用 FileBody 的 constructor 将文件名作为参数

    【讨论】:

      【解决方案2】:

      在附加文件时尝试使用addPart 的其他实现,以便您可以将文件名字段添加到HTTP 请求中。像这样的:

      FormBodyPart userFile = new FormBodyPart("userfile", new FileBody(myImageFile));
      userFile.addField("filename","NEWNAMEOFILE.jpg");
      multipartEntity.addPart(userFile);
      

      【讨论】:

        【解决方案3】:

        renameTo() 是否可能返回 false?您应该检查您的返回值,尤其是使用 renameTo()。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-12-19
          • 1970-01-01
          • 2023-04-02
          • 2019-02-27
          • 2021-06-26
          • 2017-09-28
          • 2017-11-10
          相关资源
          最近更新 更多