7

イメージをサーブレットにアップロードしようとしていますが、自動テスト中に時々失敗します。

何が原因か分かりますか?

サーバー上のコードは次のとおりです。

    @ResponseBody
    @RequestMapping(method = RequestMethod.POST)
    public String upload(HttpServletRequest request) throws Exception {
     BufferedImage image = null;

     @SuppressWarnings("unchecked")
     List<FileItem> items = new ServletFileUpload(
           new DiskFileItemFactory()).parseRequest(request);

    Logger.log(LogLevel.INFO, "Upload contains " + items.size()
            + " items.");
    int i = 0;
    for (FileItem item : items) {
        Logger.log(LogLevel.INFO, "\tItem " + (i++) + ". Name:\t"
                + item.getName() + ", Type:\t" + item.getContentType());

        // File is of type "file"
        if (!item.isFormField()) {
            InputStream inputStream = null;
            try {
                inputStream = item.getInputStream();
                if (inputStream.available() == 0) {
                    Logger.log(LogLevel.WARN,
                            "Item shows file type, but no bytes are available");
                }
                image = ImageIO.read(inputStream);
                if (image != null) {
                    break;
                }
            } catch (Exception e) {
                Logger.log(LogLevel.ERROR,
                        "There was an error reading the image. "
                                + ExceptionUtils.getFullStackTrace(e));
                throw new Exception("image provided is not a valid image");
            } finally {
                if (inputStream != null) {
                    IOUtils.closeQuietly(inputStream);
                }
            }
        }
    }

     if (image == null) {
        Logger.log(LogLevel.ERROR, "Image was supposedly read correctly, but was null afterwards");
        throw new Exception("Image provided could not be read");
     }

     //do stuff with image
     ...
    }

テストは次のとおりです。

 public void testImageUpload throws Exception {
    HttpPost httppost = new HttpPost("path/to/endpoint");
    File file=new File(imgLoc);
    FileBody bin = new FileBody(file);
    StringBody comment = new StringBody("Filename: " + file);

    MultipartEntity reqEntity = new MultipartEntity();
    reqEntity.addPart("upload-file", bin);
    reqEntity.addPart("comment", comment);
    httppost.setHeader("Accept", "application/json");
    httppost.setHeader("Connection","Keep-Alive");
    httppost.setEntity(reqEntity);
    HttpResponse response =testClient.getClient().execute(httppost);
    imgResponse=response.getStatusLine().toString();
    System.out.println(imgResponse);
    BufferedReader reader = new BufferedReader(
           new InputStreamReader(response.getEntity().getContent()));
    String line;
    while ((line = reader.readLine()) != null){
       output = output + " " +line;}
    System.out.println("Image Response: "+output);
}

失敗したときのサーバーからの出力は次のとおりです。

2013/10/02 05-53-32,287::LOG:INFO[com.example#upload:L130 -- Upload contains 2 items.]
2013/10/02 05-53-32,288::LOG:INFO[com.example#upload:L133 --        Item 0. Name:   Dog.jpg, Type:  application/octet-stream]
2013/10/02 05-53-32,288::LOG:WARN[com.example#upload:L140 -- Item shows file type, but no bytes are available]
2013/10/02 05-53-32,289::LOG:INFO[com.example#upload:L133 --        Item 1. Name:   null, Type:     text/plain; charset=ISO-8859-1]
2013/10/02 05-53-32,290::LOG:ERROR[com.example#upload:L159 -- Image was supposedly read correctly, but was null afterwards]

画像のアップロードから例外をキャッチし、応答コード 422 をクライアントに送り返すため、テストでimgResponseは失敗ケースである ==422 を取得します。

注: これは、テストを実行するときにのみ発生します。

4

6 に答える 6

2

Apache Commons FileUpload を使用してファイルをアップロードするための段階的な構成を次に示します。

1. 次のコンポーネントの依存関係 jar を追加します。Maven の依存関係は次のとおりです。

pom.xml

 <dependencies>
     <!-- Spring 3 MVC  -->
     <dependency>
         <groupId>org.springframework</groupId>
         <artifactId>spring-webmvc</artifactId>
         <version>3.2.4.RELEASE</version>
     </dependency>
     <!-- Apache Commons file upload  -->
     <dependency>
         <groupId>commons-fileupload</groupId>
         <artifactId>commons-fileupload</artifactId>
         <version>1.2.2</version>
     </dependency>
     <!-- Apache Commons IO -->
     <dependency>
         <groupId>org.apache.commons</groupId>
         <artifactId>commons-io</artifactId>
         <version>1.3.2</version>
     </dependency>
     <!-- JSTL for c: tag -->
     <dependency>
         <groupId>jstl</groupId>
         <artifactId>jstl</artifactId>
         <version>1.2</version>
     </dependency>
 </dependencies>

Maven を使用していない場合は、オンラインの Maven リポジトリからそれぞれの jar をダウンロードします。

2. FileUploadForm モデルを作成する

FileUploadForm.java

import java.util.List;
import org.springframework.web.multipart.MultipartFile;

public class FileUploadForm {

    private List<MultipartFile> files;

    //Getter and setter methods
}

3. リゾルバーを MVC 構成ファイルに追加する

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

    <!-- one of the properties available; the maximum file size in bytes -->
    <property name="maxUploadSize" value="100000"/>
</bean>

4. FileUploadController を書く

FileUploadController.java

@Controller
public class FileUploadController {
     
    @RequestMapping(value = "/show", method = RequestMethod.GET)
    public String displayForm() {
        return "file_upload_form";
    }
     
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public String save(
            @ModelAttribute("uploadForm") FileUploadForm uploadForm,
                    Model map) {
         
        List<MultipartFile> files = uploadForm.getFiles();
 
        List<String> fileNames = new ArrayList<String>();
         
        if(null != files && files.size() > 0) {
            for (MultipartFile multipartFile : files) {
 
                String fileName = multipartFile.getOriginalFilename();
                fileNames.add(fileName);
                //Handle file content - multipartFile.getInputStream()
 
            }
        }
         
        map.addAttribute("files", fileNames);
        return "file_upload_success";
    }
}

5.jspビューを書く

file_upload_form.jsp

<html>
<head>
    <title>Spring MVC Multiple File Upload</title>
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
    //add more file components if Add is clicked
    $('#addFile').click(function() {
        var fileIndex = $('#fileTable tr').children().length - 1;
        $('#fileTable').append(
                '<tr><td>'+
                '   <input type="file" name="files['+ fileIndex +']" />'+
                '</td></tr>');
    });

});
</script>
</head>
<body>
<h1>Spring Multiple File Upload example</h1>

<form method="post" action="save.html"
        **enctype="multipart/form-data"**>

    <p>Select files to upload. Press Add button to add more file inputs.</p>

    <input id="addFile" type="button" value="Add File" />
    <table id="fileTable">
        <tr>
            <td><input name="files[0]" type="file" /></td>
        </tr>
        <tr>
            <td><input name="files[1]" type="file" /></td>
        </tr>
    </table>
    <br/><input type="submit" value="Upload" />
</form>
</body>
</html>

参照: http://docs.spring.io/spring/docs/3.2.4.RELEASE/spring-framework-reference/html/mvc.html#mvc-multipart

于 2013-10-16T06:00:15.867 に答える
0

私は2つの条件の下でこれに遭遇しました。1 つはディスク容量が少なくなったときで、もう 1 つは少し負荷テストを行っていたときです。

仕組みのページを見ると、ツールで項目をディスクにダンプしたり、メモリに保持したりできます。あるケースでは、テスト中にドライブがいっぱいになり、別のケースではアイテムをメモリに保持していましたが、負荷によってメモリ制限が吹き飛ばされました。

どのように設定していますか?テストに使用している画像のサイズはどれくらいですか? テスト中に何回アップロードしますか? この情報があれば、もう少しお役に立てるはずです。

于 2013-10-16T14:46:53.650 に答える
0

このコードは現在私のサイトで使用されており、魅力的に機能します:

package com.example;

import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.imageio.ImageIO;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

@Controller
@RequestMapping("/api/media")
public class ImageRestService {

    private static final Logger LOG = LoggerFactory.getLogger(ImageRestService.class);

    @RequestMapping(value = "/uploadtemp", method = RequestMethod.POST)
    public String upload(@RequestParam(value = "image") MultipartFile image) {
        try {
            BufferedImage bufferedImage = ImageIO.read(image.getInputStream());
            // process image here
        } catch (IOException e) {
            LOG.error("failed to process image", e);
            return "failure/view/name";
        }
        return "success/view/name";
    }

}
于 2013-10-16T21:51:07.983 に答える
0

あなたのコンテンツ タイプは application/octet-stream のようです。リクエストに以下のヘッダーを追加して、試してみてください

("Content-Type", "multipart/form-data");
于 2013-10-02T15:14:45.027 に答える