Springboot项目使用java写图片上传的功能代码
以下是一个使用Spring Boot实现图片上传的示例代码:
- 创建一个上传图片的控制器类
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
@RestController
@RequestMapping("/api")
public class FileUploadController {
private static final String UPLOAD_DIR = "uploads";
@PostMapping("/upload")
public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
String fileName = StringUtils.cleanPath(file.getOriginalFilename());
String uploadDir = request.getServletContext().getRealPath("") + UPLOAD_DIR;
try {
FileUploadUtil.saveFile(uploadDir, fileName, file);
} catch (IOException e) {
return new ResponseEntity<>("Could not upload the file: " + fileName, HttpStatus.BAD_REQUEST);
}
return new ResponseEntity<>("File uploaded successfully: " + fileName, HttpStatus.OK);
}
}
- 创建一个文件上传工具类
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class FileUploadUtil {
public static void saveFile(String uploadDir, String fileName, MultipartFile multipartFile) throws IOException {
Path uploadPath = Paths.get(uploadDir);
if (!Files.exists(uploadPath)) {
Files.createDirectories(uploadPath);
}
try {
multipartFile.transferTo(new File(uploadDir + "/" + fileName));
} catch (IOException e) {
throw new IOException("Could not save file: " + fileName, e);
}
}
}
- 在application.properties文件中配置文件上传的最大大小
spring.servlet.multipart.max-file-size=10MB
这样,你就可以在Spring Boot应用程序中使用Java编写图片上传功能了
原文地址: https://www.cveoy.top/t/topic/hhay 著作权归作者所有。请勿转载和采集!