java中图片上传后台代码怎么写
时间: 2023-09-01 07:08:36 浏览: 46
以下是一个简单的Java图片上传的后端代码示例:
```java
import java.io.File;
import java.io.IOException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
@Controller
public class ImageUploadController {
@PostMapping("/upload-image")
public String uploadImage(@RequestParam("image") MultipartFile image) {
// 判断文件是否为空
if (image.isEmpty()) {
return "上传文件为空";
}
try {
// 获取文件名和扩展名
String fileName = image.getOriginalFilename();
String extension = fileName.substring(fileName.lastIndexOf(".") + 1);
// 检查文件类型是否为图片
if (!extension.equalsIgnoreCase("jpg") && !extension.equalsIgnoreCase("png")) {
return "上传文件不是图片";
}
// 将图片保存到本地磁盘
image.transferTo(new File("/path/to/save/image/" + fileName));
return "图片上传成功!";
} catch (IOException e) {
e.printStackTrace();
return "图片上传失败:" + e.getMessage();
}
}
}
```
在上面的代码中,我们使用了Spring MVC框架,通过使用`@PostMapping`注解将一个POST请求映射到`/upload-image`路径上。在方法中,我们使用`@RequestParam`注解来接收上传的图片,然后判断图片是否为空,获取图片名和扩展名,并检查文件类型是否为图片。最后将图片保存到本地磁盘,并返回一个成功或失败的消息。