以下是一个简单的Java文件上传接口的示例代码:
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
@RestController
public class FileUploadController {
@PostMapping("/upload")
public ResponseEntity<String> uploadFile(@RequestPart("file") MultipartFile file) {
try {
// 获取文件名
String fileName = file.getOriginalFilename();
// 执行文件上传操作,这里只是简单地打印文件名
System.out.println("上传的文件名:" + fileName);
return ResponseEntity.ok("文件上传成功");
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("文件上传失败");
}
}
}
这个示例使用Spring Boot框架编写了一个文件上传的接口。在uploadFile方法中,通过@RequestPart注解将文件作为请求的一部分进行接收。然后可以根据需要对文件进行处理,这里只是简单地打印了文件名。你可以根据自己的需求对文件进行更复杂的处理,比如保存到指定的目录、检查文件类型等。此外,还可以添加其他参数来接收额外的表单数据。请注意,上述代码仅为示例,实际情况下可能需要根据具体的框架和需求进行适当的调整。