簡體   English   中英

使用Android上傳文件時,如何重命名文件?

[英]How do I rename a file when I'm uploading it with Android?

我有下面的代碼工作:

      MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
      entity.addPart("userfile", new FileBody(f));
      httppost.setEntity(entity);
      HttpResponse response = httpclient.execute(httppost);

問題是File f的名稱是“ abc-temp.jpg”,我希望在上載時將其命名為“ xyz.jpg”。 我不想重命名設備上的文件, 用於上傳。

這樣做的最佳方法是什么?

確實有可能,事實上我已經做到了。

                    FileBody mFileBody = new FileBody(f);
                    String mUploadFileName = "xyz.jpg";

                FormBodyPart mFormBodyPart = new FormBodyPart("userfile", mFileBody)
                {
                    @Override
                    protected void generateContentDisp(ContentBody body) {
                        StringBuilder buffer = new StringBuilder();
                        buffer.append("form-data; name=\"");
                        buffer.append("userfile");
                        buffer.append("\"");
                        buffer.append("; filename=\""+mUploadFileName+"\"");
                        addField(MIME.CONTENT_DISPOSITION, buffer.toString());
                    }
                };
                multipartContent.addPart(mFormBodyPart);

我不確定它是否會起作用,但是您可以創建一個將從FileBody繼承並覆蓋getFilename()方法的類。

我認為應該可以解決問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM