2011-11-30 83 views
0

我需要以特定名称上传图像到我的服务器,但理想情况下,我想仍然保留以原始文件名存储在设备上的图像。这是我试过的:在上传到服务器之前更改文件的名称

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()); 
    } 

如何更改文件名?

回答

1

附加文件时,这样你就可以在文件名字段添加到HTTP请求中使用的addPart其他执行尝试。这样的事情:

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

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

相关问题