我正在尝试从java spring控制器调用一个webservice。下面是代码
private void storeImages(MultipartHttpServletRequest multipartRequest) {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(
"http://localhost:8080/dream/storeimages.htm");
MultipartFile multipartFile1 = multipartRequest.getFile("file1");
MultipartEntity multipartEntity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
multipartEntity.addPart("file1",
new ByteArrayBody(multipartFile1.getBytes(),
multipartFile1.getContentType(),
multipartFile1.getOriginalFilename()));
postRequest.setEntity(multipartEntity);
HttpResponse response = httpClient.execute(postRequest);
if (response.getStatusLine().getStatusCode() != 201) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatusLine().getStatusCode());
}
}上面只是部分代码。我正在尝试确定如何在服务器端检索它。在服务器端,我有以下Spring控制器代码
@RequestMapping(value = "/storeimages.htm", method = RequestMethod.POST)
public ModelAndView postItem(HttpServletRequest request,
HttpServletResponse response) {
logger.info("Inside /secure/additem/postitem.htm");
try {
// How to get the MultipartEntity object here. More specifically i
// want to get back the Byte array from it
} catch (Exception ex) {
ex.printStackTrace();
}
return new ModelAndView("success");
}我执行了这段代码,我的控制权将转到服务器端。但是我被困在如何从multipartentity对象取回字节数组的问题上。
编辑需求:以下是需求。用户上传图片从网站(这是完成和工作)的控制后,表单提交到Spring控制器(这是完成和工作)在Spring控制器中,我使用多部分来获得表单的内容。现在我想调用一个webservices,它会将图像字节数组发送到镜像服务器。(这需要完成)在镜像服务器上,我想接收这个webservice请求,从HTTPServlerRequest获取所有字段,存储图像并返回(需要完成)
发布于 2012-08-28 05:07:44
终于解决了。以下是对我起作用的方法。
客户端
private void storeImages(HashMap<String, MultipartFile> imageList) {
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost("http://localhost:8080/dream/storeimages.htm");
MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
Set set = imageList.entrySet();
Iterator i = set.iterator();
while(i.hasNext()) {
Map.Entry me = (Map.Entry)i.next();
String fileName = (String)me.getKey();
MultipartFile multipartFile = (MultipartFile)me.getValue();
multipartEntity.addPart(fileName, new ByteArrayBody(multipartFile.getBytes(),
multipartFile.getContentType(), multipartFile.getOriginalFilename()));
}
postRequest.setEntity(multipartEntity);
HttpResponse response = httpClient.execute(postRequest);
if (response.getStatusLine().getStatusCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatusLine().getStatusCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));
String output;
while ((output = br.readLine()) != null) {
logger.info("Webservices output - " + output);
}
httpClient.getConnectionManager().shutdown();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}服务器端
@RequestMapping(value = "/storeimages.htm", method = RequestMethod.POST)
public void storeimages(HttpServletRequest request, HttpServletResponse response)
{
logger.info("Inside /secure/additem/postitem.htm");
try
{
//List<Part> formData = new ArrayList(request.getParts());
//Part part = formData.get(0);
//Part part = request.getPart("file1");
//String parameterName = part.getName();
//logger.info("STORC IMAGES - " + parameterName);
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
Set set = multipartRequest.getFileMap().entrySet();
Iterator i = set.iterator();
while(i.hasNext()) {
Map.Entry me = (Map.Entry)i.next();
String fileName = (String)me.getKey();
MultipartFile multipartFile = (MultipartFile)me.getValue();
logger.info("Original fileName - " + multipartFile.getOriginalFilename());
logger.info("fileName - " + fileName);
writeToDisk(fileName, multipartFile);
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
public void writeToDisk(String filename, MultipartFile multipartFile)
{
try
{
String fullFileName = Configuration.getProperty("ImageDirectory") + filename;
FileOutputStream fos = new FileOutputStream(fullFileName);
fos.write(multipartFile.getBytes());
fos.close();
}
catch (Exception ex)
{
ex.printStackTrace();
}
}发布于 2012-08-26 13:01:49
在我的项目中,我们使用来自com.oreilly.servlets的MultipartParser来处理对应于multipart请求的HttpServletRequests,如下所示:
// Should be able to handle multipart requests upto 1GB size.
MultipartParser parser = new MultipartParser(aReq, 1024 * 1024 * 1024);
// If the content type is not multipart/form-data, this will be null.
if (parser != null) {
Part part;
while ((part = parser.readNextPart()) != null) {
if (part instanceof FilePart) {
// This is an attachment or an uploaded file.
}
else if (part instanceof ParamPart) {
// This is request parameter from the query string
}
}
}希望这能有所帮助。
发布于 2012-08-26 14:56:26
您可以使用Springs Mutlipart支持来代替手动完成所有这些工作
控制器可以像这样工作(这个例子使用一个命令对象来存储额外的用户输入-- (这是一个工作项目的例子))。
@RequestMapping(method = RequestMethod.POST)
public ModelAndView create(@Valid final DocumentCreateCommand documentCreateCommand,
final BindingResult bindingResult) throws IOException {
if (bindingResult.hasErrors()) {
return new ModelAndView("documents/create", "documentCreateCommand", documentCreateCommand);
} else {
Document document = this.documentService.storeDocument(
documentCreateCommand.getContent().getBytes(),
StringUtils.getFilename(StringUtils.cleanPath(documentCreateCommand.getContent().getOriginalFilename())));
//org.springframework.util.StringUtils
return redirectToShow(document);
}
}
@ScriptAssert(script = "_this.content.size>0", lang = "javascript", message = "{validation.Document.message.notDefined}")
public class DocumentCreateCommand {
@NotNull private org.springframework.web.multipart.MultipartFile content;
Getter/Setter
}要启用Spring Multipart支持,您需要配置一些东西:
web.xml (在CharacterEncodingFilter之后HttpMethodFilter之前添加org.springframework.web.multipart.support.MultipartFilter )
<filter>
<filter-name>MultipartFilter</filter-name>
<filter-class>org.springframework.web.multipart.support.MultipartFilter</filter-class>
<!-- uses the bean: filterMultipartResolver -->
</filter>
<filter-mapping>
<filter-name>MultipartFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>在应用程序核心(而不是MVC Servlet)的Spring配置中,添加以下内容
<!-- allows for integration of file upload functionality, used by an filter configured in the web.xml -->
<bean class="org.springframework.web.multipart.commons.CommonsMultipartResolver" id="filterMultipartResolver" name="filterMultipartResolver">
<property name="maxUploadSize" value="100000000"/>
</bean>然后,您还需要commons fileupload库,因为Spring只是某种MultipartFile
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.2.1</version>
</dependency>有关更多详细信息:@请参阅Spring Reference, Chapter 15.8 Spring's multipart (fileupload) support
https://stackoverflow.com/questions/12127531
复制相似问题