MultipartFile上传图片
时间: 2023-11-20 10:58:23 浏览: 79
以下是一个使用Spring Boot实现MultipartFile上传图片的例子:
```java
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.springframework.stereotype.Controller;import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
@Controller
public class ImageUploadController {
private static String UPLOAD_FOLDER = "/path/to/upload/folder/";
@GetMapping("/")
public String index() {
return "upload";
}
@PostMapping("/upload")
public String singleFileUpload(@RequestParam("file") MultipartFile file, Model model) {
if (file.isEmpty()) {
model.addAttribute("message", "Please select a file to upload."); return "uploadStatus";
}
try {
byte[] bytes = file.getBytes();
Path path = Paths.get(UPLOAD_FOLDER + file.getOriginalFilename());
Files.write(path, bytes);
model.addAttribute("message", "You successfully uploaded '" + file.getOriginalFilename() + "'");
} catch (IOException e) {
e.printStackTrace();
}
return "uploadStatus";
}
}
```
在上面的例子中,我们首先定义了一个上传文件的文件夹路径`UPLOAD_FOLDER`,然后在`singleFileUpload`方法中,我们使用`@RequestParam`注解来获取上传的文件,然后将文件保存到指定的文件夹中。
阅读全文