I'd like to limit the size of the file that can be uploaded to an application. To achieve this, I'd like to abort the upload process from the server side when the size of the file being uploaded exceeds a limit.
Is there a way to abort an upload process from the server side without waiting the HTTP request to finish?
You can set it in the context of server, per-directory, per-file or per-location. For example, if you are permitting file upload to a particular location, say /var/www/example.com/wp-uploads and wish to restrict the size of the uploaded file to 5M = 5242880Bytes, add the following directive into your .
MultipartConfig , is used to indicate that the servlet on which it is declared expects requests to be made using the multipart/form-data MIME type. Servlets that are annotated with @MultipartConfig can retrieve the Part components of a given multipart/form-data request by calling the request.
fileSizeThreshold: The file size in bytes after which the file will be temporarily stored on disk. The default size is 0 bytes. MaxFileSize: The maximum size allowed for uploaded files, in bytes.
Open the file in any text editor and add the following code. @ini_set( 'upload_max_size' , '20M' ); @ini_set( 'post_max_size', '13M'); @ini_set( 'memory_limit', '15M' ); Save your changes, and it should increase your file upload size.
With JavaEE 6 / Servlet 3.0 the preferred way of doing that would be to use the @MultipartConfig annotation on your servlet like this:
@MultipartConfig(location="/tmp", fileSizeThreshold=1024*1024,
maxFileSize=1024*1024*5, maxRequestSize=1024*1024*5*5)
public class UploadFileServiceImpl extends HttpServlet ...
You can do something like this (using the Commons library):
public class UploadFileServiceImpl extends HttpServlet
{
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException
{
response.setContentType("text/plain");
try
{
FileItem uploadItem = getFileItem(request);
if (uploadItem == null)
{
// ERROR
}
// Add logic here
}
catch (Exception ex)
{
response.getWriter().write("Error: file upload failure: " + ex.getMessage());
}
}
private FileItem getFileItem(HttpServletRequest request) throws FileUploadException
{
DiskFileItemFactory factory = new DiskFileItemFactory();
// Add here your own limit
factory.setSizeThreshold(DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD);
ServletFileUpload upload = new ServletFileUpload(factory);
// Add here your own limit
upload.setSizeMax(DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD);
List<?> items = upload.parseRequest(request);
Iterator<?> it = items.iterator();
while (it.hasNext())
{
FileItem item = (FileItem) it.next();
// Search here for file item
if (!item.isFormField() &&
// Check field name to get to file item ...
{
return item;
}
}
return null;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With