アップロードするファイルのサイズを確認し、ファイルがメモリに完全に読み込まれないようにしたい。CommonsMultipartFile を使用しています。アップロードされたファイルは処理され、DB に保存されます。AbstractCoupleUploadController クラスは、ファイルを含む着信要求を処理します。
public abstract class AbstractCoupleUploadController<T extends Serializable> extends RemoteServiceServlet implements ServletContextAware,
UploadServlet<WorkshopHistoryModel>
{
...
@RequestMapping(method={RequestMethod.GET,RequestMethod.POST})
public ModelAndView handleRequest(@RequestParam("firstFile") CommonsMultipartFile firstFile,
@RequestParam("secondFile") CommonsMultipartFile secondFile, HttpServletRequest request, HttpServletResponse response)
{
synchronized(this)
{
initThreads();
perThreadRequest.set(request);
perThreadResponse.set(response);
}
handleUpload(firstFile,secondFile,request,response);
response.getWriter().flush();
response.flushBuffer();
return null;
}
private void handleUpload(CommonsMultipartFile firstFile, CommonsMultipartFile secondFile, HttpServletRequest request,
HttpServletResponse response) throws IOException
{
response.setContentType("text/html");
if(firstFile.getSize() == 0 || secondFile.getSize() == 0)
{
response.getWriter().print(AppConstants.UPLOAD_ZERO_SIZE_FILE);
return;
}
// other validations
// uploading:
try
{
String content = request.getParameter(CoupleUploadPanel.CONTENT);
T model = deserialize(content);
UploadResultModel resultModel = upload(model,firstFile,secondFile); // it's implemented in UploadFileServletImpl
if(resultModel.hasCriticalError())
{
response.getWriter().print(AppConstants.UPLOAD_FAIL + "," + String.valueOf(resultModel.getWorkshopHistoryId()));
}
else
{
response.getWriter().print(AppConstants.UPLOAD_SUCCESS + "," + String.valueOf(resultModel.getWorkshopHistoryId()));
}
}
catch(ProcessRequestException e)
{
// write upload error description in response.getWriter()
}
catch(Exception e)
{
e.printStackTrace();
response.getWriter().print(AppConstants.UPLOAD_UNKOWN_ERROR);
}
}
...
}
app-servlet.xml (file.upload.max_size=9437184) に multipartResolver Bean があり、UploadSizeExceededExceptions を処理するための maxUploadSizeExceededExceptionHandler Bean もあります。
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="${file.upload.max_size}" />
</bean>
<bean id="maxUploadSizeExceededExceptionHandler" class="com.insurance.ui.server.uploadfile.MaxUploadSizeExceededExceptionHandler">
<property name="order" value="1"/>
</bean>
私の maxUploadSizeExceededExceptionHandler:
public class MaxUploadSizeExceededExceptionHandler implements HandlerExceptionResolver, Ordered
{
private int order;
@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
{
if(ex instanceof MaxUploadSizeExceededException)
{
try
{
response.getWriter().print(ErrorConstants.UPLOAD_SIZE_EXCEED + "," + (((MaxUploadSizeExceededException) ex).getMaxUploadSize()/(1024*1024)));
response.getWriter().flush();
response.flushBuffer();
return new ModelAndView();
}
catch(IOException e)
{
}
}
return null;
}
...
}
非常に大きなファイル (${file.upload.max_size} を超える、約 700MB) をアップロードすると、CommonsMultipartResolver は MaxUploadSizeExceededException をすぐにスローします。ブラウザのアップロード進行状況バーは、ファイルがまだアップロード中であることを示しています!! なんで?
更新:私は使用しています:
- 春-*-3.0.5.RELEASE
- commons-fileupload-1.1.1
また、試しました:
- 春-*-3.1.2.RELEASE
- commons-fileupload-1.3
そして私のAS:
- Tomcat 6 (開発中)
- Jboss 7 (本番)
更新 2:クライアント側では、GWT を使用しています (問題ではないと思います):
submitRequestButton をクリックすると、アップロードが開始されます。
@UiHandler("submitRequestButton")
public void submitRequestButtonClick(ClickEvent event)
{
try
{
// some validation
submitRequestButton.setEnabled(false);
uploadPanel.upload(model.getWorkshopHistoryModel()); // uploadPanel is from the CoupleUploadPanel type
}
catch(ValidationException exception)
{
// handle validation errors
}
catch(SerializationException e)
{
// handle serialization errors
}
}
アップロード用の CoupleUploadPanel ウィジェットがあります (2 つのファイル):
public class CoupleUploadPanel<T extends Serializable> extends FormPanel
{
public final static String CONTENT = "content";
private static final String FIRST_FILE = "firstFile";
private static final String SECOND_FILE = "secondFile";
private Hidden contentInput;
private FileUpload firstFileUploadInput;
private FileUpload secondFileUploadInput;
private SerializationStreamFactory factory;
public CoupleUploadPanel(UploadServletAsync<T> factory)
{
this(null,factory);
}
public CoupleUploadPanel(String url, UploadServletAsync<T> factory)
{
this.factory = (SerializationStreamFactory) factory;
if(url != null)
{
setAction(url);
}
init();
}
public CoupleUploadPanel(String target, String url, UploadServletAsync<T> factory)
{
super(target);
this.factory = (SerializationStreamFactory) factory;
if(url != null)
{
setAction(url);
}
init();
}
private void init()
{
setMethod("POST");
setEncoding(ENCODING_MULTIPART);
firstFileUploadInput = new FileUpload();
firstFileUploadInput.setName(CoupleUploadPanel.FIRST_FILE);
secondFileUploadInput = new FileUpload();
secondFileUploadInput.setName(CoupleUploadPanel.SECOND_FILE);
contentInput = new Hidden();
contentInput.setName(CONTENT);
VerticalPanel panel = new VerticalPanel();
panel.add(firstFileUploadInput);
panel.add(secondFileUploadInput);
panel.add(contentInput);
add(panel);
}
public void upload(T input) throws SerializationException
{
contentInput.setValue(serialize(input));
submit();
}
private String serialize(T input) throws SerializationException
{
SerializationStreamWriter writer = factory.createStreamWriter();
writer.writeObject(input);
return writer.toString();
}
}
UploadServletAsync を CoupleUploadPanel コンストラクターに渡す必要があります。UploadServletAsync および UploadServlet インターフェース:
public interface UploadServletAsync<T extends Serializable>
{
void upload(T model, AsyncCallback<Void> callback);
}
public interface UploadServlet<T extends Serializable> extends RemoteService
{
void upload(T model);
}
したがって、uploadPanelは次のようにインスタンス化されます。
uploadPanel= new CoupleUploadPanel<WorkshopHistoryModel>((UploadFileServletAsync) GWT.create(UploadFileServlet.class));
uploadPanel.setAction(UploadFileServlet.URL);
そして、 submitCompeleteHandler が uploadPanel に追加されました (送信が完了し、結果がクライアント側に渡されると、onSumbitComplete()が呼び出されます):
uploadPanel.addSubmitCompleteHandler(new SubmitCompleteHandler()
{
@Override
public void onSubmitComplete(SubmitCompleteEvent event)
{
String s = event.getResults(); //contains whatever written by response.getWriter()
if(s == null)
{
// navigate to request list page
}
else
{
String[] response = s.split(",");
// based on response:
// show error messages if any error occurred in file upload
// else: navigate to upload result page
}
}
});
UploadFileServlet および UploadFileServletAsync インターフェイス:
public interface UploadFileServlet extends UploadServlet<WorkshopHistoryModel>
{
String URL = "**/uploadFileService.mvc";
}
public interface UploadFileServletAsync extends UploadServletAsync<WorkshopHistoryModel>
{
public static final UploadFileServletAsync INSTANCE = GWT.create(UploadFileServlet.class);
}
サーバー側: UploadFileServletImpl は AbstractCoupleUploadController を拡張し、upload()メソッド (アップロード プロセス)を実装します。
@RequestMapping(UploadFileServlet.URL)
public class UploadFileServletImpl extends AbstractCoupleUploadController<WorkshopHistoryModel>
{
...
@Override
protected UploadResultModel upload(WorkshopHistoryModel model, MultipartFile firstFile, MultipartFile secondFile)
throws ProcessRequestException
{
return workshopHistoryService.submitList(model.getWorkshop(),firstFile,secondFile);
}
...
}