Spring upload file size limit

2020-02-12 09:45发布

问题:

I'm using Spring Boot for my application, and I want to upload some files into my database. I used a tutorial to achive this, and it works fine. My problem is that I don't know how to set max file size to upload. The default is 1MB but that's just not enough for me.

I added these lines to my application.properties:

spring.http.multipart.max-file-size = 100MB

spring.http.multipart.max-request-size = 100MB

but it didn't help.

My code:

FileService.java

@Service
public class FileService {
@Autowired
FileRepository fileRepository;
public Response uploadFile(MultipartHttpServletRequest request) throws  IOException {

    Response response = new Response();
    List fileList = new ArrayList();

    Iterator<String> itr = request.getFileNames();

    while (itr.hasNext()) {
        String uploadedFile = itr.next();
        MultipartFile file = request.getFile(uploadedFile);
        String mimeType = file.getContentType();
        String filename = file.getOriginalFilename();
        byte[] bytes = file.getBytes();

        File newFile = new File(filename, bytes, mimeType);
        File savedFile = fileRepository.saveAndFlush(newFile);
        savedFile.setFile(null);
        fileList.add(savedFile);
    }

    response.setReport(fileList);
    return response;
}
}

FileController.java

@RestController
@RequestMapping("/file")
public class FileController {

    @Autowired
    FileService fileService;
@RequestMapping(value = "/upload", method = RequestMethod.POST)
    public Response uploadFile(MultipartHttpServletRequest request) throws IOException{
        return fileService.uploadFile(request);
     }
}

This code is just fine, it works perfectly, I just can't set max file size.

Thanks in advance.

回答1:

With Spring earlier than 4.0 the right properties are

multipart.maxFileSize

multipart.maxRequestSize

From Spring 4 these were changed to

spring.http.multipart.max-file-size

spring.http.multipart.max-request-size



回答2:

For me worked (in Spring Boot 2.0.0):

spring.servlet.multipart.max-file-size=-1


回答3:

This configuration worked for me:

spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB