簡體   English   中英

處理MaxUploadSizeExceededException無法停止上傳文件

[英]Handling MaxUploadSizeExceededException can not stop uploading file

我想檢查上傳文件的大小並防止文件完全加載到內存中。 我正在使用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中有一個multipartResolver bean(file.upload.max_size = 9437184),還有一個用於處理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,我正在捕捉並處理它(寫在response.getWriter())。但我的問題:我的瀏覽器上傳 - 進度條顯示文件仍在上傳!! 為什么?

更新:我正在使用:

  • 春天 - * - 3.0.5.RELEASE
  • 公地文件上傳-1.1.1

並嘗試過:

  • 春天 - * - 3.1.2.RELEASE
  • 公地文件上傳-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小部件(兩個文件):

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

    ...
}

好吧,afaik Spring(一個servlet和一些過濾器)沒有觀察到上傳過程,只是處理完成過程的結果。 那是因為上傳是由Tomcat自己處理的(提示: web.xml有一個上傳大小限制選項)。 因此,可能會導致上載失敗(Spring不會被注意到)或上傳過大的文件。 並且只有當第二次發生時,特定的過濾器/攔截器才能拒絕該過程。

在我的上一次設置中,我在Tomcat前面使用Nginx作為代理:

  1. 如果您的瀏覽器發送實際文件大小(現代瀏覽器,但至少IE7?或IE8?沒有),如果大小超過定義的限制,Nginx將發送500。
  2. 我不是100%肯定:如果上傳的大小超過指定的限制,Nginx也會發送500。 這也將取消與Tomcat的底層連接。

我們使用以下方法:

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

}

作為第一次嘗試,我將在MaxUploadSizeExceededExceptionHandler調用response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR)

然后我會檢查 兩個 SO問題,看看它們是否會包含一些我可以嘗試的有用信息。

如果這沒有幫助,我會調查GwtUpload的來源,看看他們是如何實現的(或者只是開始使用他們的實現)。

yourfile.getFile().getSize() > Long.parseLong(153600);

此代碼將批准上傳小於150 kb的文件。 如果超過150 kb,您可以發送任何錯誤信息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM