Spring implements file upload function
- 2020-06-01 09:56:24
- OfStack
In this article, we will do a file upload function of Spring:
1. Create an Maven web project and then configure the pom.xml file to add dependencies:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>1.0.2.RELEASE</version>
</dependency>
2. Enter 1 form in the index.jsp file in the webapp directory:
<html>
<body>
<form method="POST" enctype="multipart/form-data"
action="/upload">
File to upload: <input type="file" name="file"><br /> Name: <input
type="text" name="name"><br /> <br /> <input type="submit"
value="Upload"> Press here to upload the file!
</form>
</body>
</html>
This form is our simulated upload page.
3. Write Controller to handle this form:
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
@Controller
public class FileUploadController {
@RequestMapping(value="/upload", method=RequestMethod.GET)
public @ResponseBody String provideUploadInfo() {
return "You can upload a file by posting to this same URL.";
}
@RequestMapping(value="/upload", method=RequestMethod.POST)
public @ResponseBody String handleFileUpload(@RequestParam("name") String name,
@RequestParam("file") MultipartFile file){
if (!file.isEmpty()) {
try {
byte[] bytes = file.getBytes();
BufferedOutputStream stream =
new BufferedOutputStream(new FileOutputStream(new File(name + "-uploaded")));
stream.write(bytes);
stream.close();
return "You successfully uploaded " + name + " into " + name + "-uploaded !";
} catch (Exception e) {
return "You failed to upload " + name + " => " + e.getMessage();
}
} else {
return "You failed to upload " + name + " because the file was empty.";
}
}
}
4. Then we put some restrictions on the uploaded files and wrote the main method to launch the web:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.context.embedded.MultiPartConfigFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import javax.servlet.MultipartConfigElement;
@Configuration
@ComponentScan
@EnableAutoConfiguration
public class Application {
@Bean
public MultipartConfigElement multipartConfigElement() {
MultiPartConfigFactory factory = new MultiPartConfigFactory();
factory.setMaxFileSize("128KB");
factory.setMaxRequestSize("128KB");
return factory.createMultipartConfig();
}
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
5. Then visit http: / / localhost: 8080 / upload can see the page.
The above example is to achieve a single file upload function, assuming that we now want to achieve the file batch upload function, we only need to modify the above code 1 line, considering the length of the problem, the following is only posted and the above different code, no instructions and the above 1. :
1. Add batchUpload.jsp file
<html>
<body>
<form method="POST" enctype="multipart/form-data"
action="/batch/upload">
File to upload: <input type="file" name="file"><br />
File to upload: <input type="file" name="file"><br />
<input type="submit" value="Upload"> Press here to upload the file!
</form>
</body>
</html>
2. New BatchFileUploadController.java file:
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.List;
/**
* Created by wenchao.ren on 2014/4/26.
*/
@Controller
public class BatchFileUploadController {
@RequestMapping(value="/batch/upload", method= RequestMethod.POST)
public @ResponseBody
String handleFileUpload(HttpServletRequest request){
List<MultipartFile> files = ((MultipartHttpServletRequest)request).getFiles("file");
for (int i =0; i< files.size(); ++i) {
MultipartFile file = files.get(i);
String name = file.getName();
if (!file.isEmpty()) {
try {
byte[] bytes = file.getBytes();
BufferedOutputStream stream =
new BufferedOutputStream(new FileOutputStream(new File(name + i)));
stream.write(bytes);
stream.close();
} catch (Exception e) {
return "You failed to upload " + name + " => " + e.getMessage();
}
} else {
return "You failed to upload " + name + " because the file was empty.";
}
}
return "upload successful";
}
}
So a simple batch file upload function ok, is not very simple ah.
Note: the above code is for demonstration purposes only, so the coding style is arbitrary and is not recommended.