我需要从服务器端上传一个 xml 文件,其中文件的内容在一个字符串中。如何使此文件内容在服务器上上传(基本上保存)?
这就是我正在尝试的,效果很好,如果我直接给一个文件,FileBody
但如何欺骗它让文件内容作为多部分请求发送到另一个 servlet?
private def createConfiguration(def sessiontoken)
{
def xmlString=""
HttpClient httpclient = new DefaultHttpClient();
try {
HttpPost httppost = new HttpPost(fileParams.create);
//FileBody bin = new FileBody(new File("C:\\Simon\\myxml.xml"));
StringBody st = new StringBody(sessiontoken);
StringBody cfgname = new StringBody(reqParams.c_Cfgname[0]);
StringBody cfgdesc = new StringBody(reqParams.c_Cfgdesc[0]);
StringBody cfgtype = new StringBody(reqParams.c_Cfgtype[0]);
StringBody cfgfile = new StringBody(reqParams.CFGFILE[0]);
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("sessiontoken", st);
reqEntity.addPart("cfgname", cfgname);
reqEntity.addPart("cfgdesc", cfgdesc);
reqEntity.addPart("cfgenv", cfgtype);
//reqEntity.addPart("cfgfile", bin);
reqEntity.addPart("cfgfile", cfgfile);
httppost.setEntity(reqEntity);
System.out.println("executing request " + httppost.getRequestLine());
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
System.out.println("----------------------------------------");
//System.out.println(response.getStatusLine());
if (resEntity != null) {
//System.out.println("Response content length: " + resEntity.getContentLength());
xmlString=resEntity.getContent().getText()
}
EntityUtils.consume(resEntity);
} finally {
try { httpclient.getConnectionManager().shutdown(); } catch (Exception ignore) {}
}
xmlString
}
如果我使用上面的代码,我会得到以下异常
----------------------------------------
Exception while processing your Request.
No result defined for action com.abc.dc.actions.CreateConfiguration and
result input
更新
所以现在在检查了tomcat日志和其他服务器端代码之后,我知道内部dc
正在获取cfgfile
并将其设置为
public void setCfgfile(File cfgfile)
{
this.cfgfile = cfgfile
}
这给了我
java.lang.NoSuchMethodException: com.abc.dc.actions.CreateConfiguration.setCfgfile([Ljava.lang.String;)
那么如何在这里重载setCfgfile
方法public void setCfgfile(String cfgfile)
并转换cfgfile
为File
对象呢?
甚至更好,
如何将此cfgfile
字符串变量转换为FileBody
对象?