5

Java スプリング コントローラーから Web サービスを呼び出そうとしています。以下はコードです

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

このコードを実行すると、コントロールがサーバー側に移動します。しかし、マルチパーティ オブジェクトからバイト配列を取得する方法に行き詰まっています。

編集された要件: ここに要件があります。ユーザーは Web サイトから画像をアップロードします (これは完了し、機能しています) フォームの送信後にコントロールが Spring コントローラーに移動します (これは完了し、機能しています) Spring コントローラーでは、マルチパートを使用してフォームのコンテンツを取得しています。(これは完了し、機能しています)今、画像バイト配列を画像サーバーに送信するWebサービスを呼び出したいです(これを行う必要があります)画像サーバーで、このWebサービスリクエストを受信したいHTTPServlerRequestからすべてのフィールドを取得します、画像を保存して戻ります(これを行う必要があります)

4

4 に答える 4

7

最後にそれを解決しました。これが私のために働いたものです。

クライアント側

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-27T21:07:43.807 に答える
2

私のプロジェクトでは、com.oreilly.servletsのMultipartParserを使用して、次のようにリクエストにHttpServletRequests対応する処理を行っていました。multipart

// 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-26T05:01:48.797 に答える
2

すべてを手作業で行う代わりに、SpringsMutlipartサポートを使用できます

コントローラは次のように機能します(この例では、コマンドオブジェクトを使用して、追加のユーザー入力を格納します-(これは作業中のプロジェクトの例です))。

@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>

アプリケーションのCORE(MVCサーブレットではない)の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>

次に、Spring MultipartFileは一種のAddapterであるため、commonsfileuploadライブラリも必要です。

<dependency>
     <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.2.1</version>
</dependency>

詳細については、@ Springリファレンスの第15.8章を参照してください。Springのマルチパート(fileupload)サポート

于 2012-08-26T06:56:26.013 に答える
0

コントローラーへのスプリングファイルを処理します。app-config.xml で次のように指定する必要があります。

    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>

コードを次のように扱います

    MultipartEntityBuilder paramsBuilder = MultipartEntityBuilder.create();
    Charset chars = Charset.forName("UTF-8");
    paramsBuilder.setCharset(chars);

    if (null != obj.getFile()){
    FileBody fb = new FileBody(obj.getFile());
    paramsBuilder.addPart("file", fb);
    }

これは赤のマルチパート用です

private File getFile(MultipartFile file) {

    try {
        File fichero = new File(file.getOriginalFilename());
        fichero.createNewFile();
        FileOutputStream fos = new FileOutputStream(fichero);
        fos.write(file.getBytes());
        fos.close();
        return fichero;
    } catch (Exception e) {
        return null;
    }

}

これが役立つことを願っています。

于 2016-07-29T14:21:49.473 に答える