处理最大上传大小异常无法停止上传文件

我想检查上传文件的大小,并防止文件完全加载到内存中。我正在使用CommonsMultipartFile。上传的文件将被处理并保留在数据库中。摘要CoupleUploadController类处理包含文件的传入请求:

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中有一个多部分Resolver bean.xml(file.upload.max_size=9437184),还有一个maxUploadSizeExceedExceptionHandler bean用于处理UploadSizeExceedExceptions:

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

My maxUploadSizeExceedExceptionHandler:

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会立即抛出MaxUploadSizeExceedException,我正在捕获并处理它(写在responsed.getWriter()中)。但我的问题:我的浏览器上传进度条显示文件仍在上传!为什么?

更新:我正在使用:

  • 弹簧-*-3.0.5.发布
  • 共享资源-文件上传-1.1.1

并尝试了:

  • 弹簧-*-3.1.2.发布
  • 共享资源-文件上传-1.3

和我的 AS:

  • 雄猫6(开发中)
  • Jboss 7(生产中)

更新 2:在客户端,我正在使用GWT(我认为这并不重要):

通过单击提交请求按钮开始上传:

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

我有一个用于上传的FhopUploadPanel Widget(两个文件):

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

并且添加到 uploadPanel 的 SubmitCompeleteHandler(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() 方法(upload process):

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

    ...
}

答案 1

好吧,afaik Spring(一个servlet和一些过滤器)不观察上传过程,而只处理完成过程的结果。这是因为上传是由Tomcat本身处理的(提示:在中有一个上传大小限制选项)。因此,可以使上传失败(Spring不会注意到)或上传太大的文件。只有当第二次发生时,特定的过滤器/拦截器才能拒绝该过程。web.xml

在我最后的设置中,我使用Nginx作为Tomcat前面的代理:

  1. 如果您的浏览器发送实际文件大小(现代浏览器会发送,至少IE7?或IE8?不会),那么如果大小超过定义的限制,Nginx将发送500。
  2. 我不是100%确定:如果上传的大小超过指定的限制,Nginx也会发送500。这也将取消与雄猫的底层连接。

答案 2

我们使用以下方法:

public class MultipartResolver extends CommonsMultipartResolver {

public MultipartHttpServletRequest resolveMultipart(HttpServletRequest request) throws MultipartException {
    String encoding = determineEncoding(request);
    FileUpload fileUpload = prepareFileUpload(encoding);

    try {
        List fileItems = ((ServletFileUpload) fileUpload).parseRequest(request);
        MultipartParsingResult parsingResult = parseFileItems(fileItems, encoding);
        return new DefaultMultipartHttpServletRequest(
                request, parsingResult.getMultipartFiles(), parsingResult.getMultipartParameters(), parsingResult.getMultipartParameterContentTypes());
    } catch (FileUploadBase.SizeLimitExceededException ex) {
        throw new MaxUploadSizeExceededException(fileUpload.getSizeMax(), ex);
    }
    catch (FileUploadException ex) {
        throw new MultipartException("Could not parse multipart servlet request", ex);
    }
}

public void cleanupMultipart(MultipartHttpServletRequest request) {
    super.cleanupMultipart(request);
}    

public void setFileSizeMax(long fileSizeMax) {
    getFileUpload().setSizeMax(-1);
    getFileUpload().setFileSizeMax(fileSizeMax);
}

}


推荐