[英]reading Word file from POST request in grails
我正在嘗試編寫一個Groovy腳本,該腳本會將Word(docx)文件發布到我的grails應用程序上的REST處理程序中。
該請求的構造如下:
import org.apache.http.HttpEntity
import org.apache.http.HttpResponse
import org.apache.http.client.methods.HttpPost
import org.apache.http.entity.mime.MultipartEntity
import org.apache.http.entity.mime.content.FileBody
import org.apache.http.entity.mime.content.StringBody
import org.apache.http.impl.client.DefaultHttpClient
class RestFileUploader {
def sendFile(file, filename) {
def url = 'http://url.of.my.app';
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
MultipartEntity reqEntity = new MultipartEntity();
FileBody bin = new FileBody(file);
reqEntity.addPart("file", new FileBody((File)file, "application/msword"));
def normalizedFilename = filename.replace(" ", "")
reqEntity.addPart("fileName", new StringBody(normalizedFilename));
httppost.setEntity(reqEntity);
httppost.setHeader('X-File-Size', (String)file.size())
httppost.setHeader('X-File-Name', filename)
httppost.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document; charset=utf-8')
println "about to post..."
HttpResponse restResponse = httpclient.execute(httppost);
HttpEntity resEntity = restResponse.getEntity();
def responseXml = resEntity.content.text;
println "posted..."
println restResponse
println resEntity
println responseXml.toString()
return responseXml.toString()
}
}
在接收控制器上,我從請求中讀取了所需的標頭,然后嘗試像這樣訪問文件:
def inStream = request.getInputStream()
我最終寫出了一個損壞的Word文件,通過檢查文件的大小和內容,看來我的控制器正在寫出整個請求,而不僅僅是文件。
我也嘗試過這種方法:
def filePart = request.getPart('file')
def inStream = filePart.getInputStream()
在這種情況下,我最終得到一個空的輸入流,而沒有任何內容被寫出來。
我覺得這里缺少一些簡單的東西。 我究竟做錯了什么?
您將需要進行兩項更改:
httppost.setHeader('Content-Type'...
文件上載HTTP POST請求必須具有內容類型multipart/form-data
(構造多部分HttpPost時由HttpClient自動設置) reqEntity.addPart("file", ...
更改為: reqEntity.addPart("file", new FileBody(file))
,或使用其他不推薦使用的FileBody
構造函數之一指定有效的內容類型,並charset( API鏈接 )這假設您的file
方法參數的類型為java.io.File
-從您的代碼段中我不清楚。 然后,如dmahapatro所建議的那樣,您應該能夠使用以下命令讀取文件: request.getFile('file')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.