gpt4 book ai didi

java - 处理 MaxUploadSizeExceededException 不能停止上传文件

转载 作者:IT老高 更新时间:2023-10-28 13:57:56 28 4
gpt4 key购买 nike

我想检查上传文件的大小并阻止文件完全加载到内存中。我正在使用 CommonsMultipartFile。上传的文件将被处理并保存在数据库中。 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())。但是 < strong>我的问题:我的浏览器上传进度条显示文件还在上传!!为什么?

更新:我正在使用:

  • Spring-*-3.0.5.RELEASE
  • commons-fileupload-1.1.1

也试过了:

  • Spring-*-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 小部件用于上传(两个文件):

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 接口(interface):

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 接口(interface):

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 的底层连接。

关于java - 处理 MaxUploadSizeExceededException 不能停止上传文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19717418/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com